Java:将字符写入/读取到文件会产生不同的结果
我正在尝试将一个简单的字符写入一个文件并读回。将字符写入文件似乎工作正常(至少在十六进制编辑器中是这样)。当我把这个字符读回内存时,它是一个完全不同的值。下面是我的示例代码:Java:将字符写入/读取到文件会产生不同的结果,java,file,io,Java,File,Io,我正在尝试将一个简单的字符写入一个文件并读回。将字符写入文件似乎工作正常(至少在十六进制编辑器中是这样)。当我把这个字符读回内存时,它是一个完全不同的值。下面是我的示例代码: public class myclass { public static void main(String[] args) { char myChar = 158; // let myChar = 158 System.out.println("myChar = "+(int)myChar);
public class myclass {
public static void main(String[] args) {
char myChar = 158; // let myChar = 158
System.out.println("myChar = "+(int)myChar); // prints 158. Good.
try {
FileOutputStream fileOut = new FileOutputStream("readthis");
fileOut.write(myChar);
fileOut.close();
} catch (IOException e) {
System.exit(1);
}
// If I examine the "readthis" file, there is one byte that has a value of
// of '9E' or 158. This is what I'd expect.
// Lets try to now read it back into memory
char readChar = 0;
try {
int i = 0;
FileInputStream fstream = new FileInputStream("readthis");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
readChar = (char)br.read();
in.close();
} catch (IOException e) {
System.exit(1);
}
// Now, if we look at readChar, it's some value that's not 158!
// Somehow it got read into as 382!
// Printing this value results in 382
System.out.println("readChar = "+(int)readChar);
}
}
我的问题是,这是怎么发生的?我希望readChar等于我写的原始值(158),但我不确定我做错了什么。任何帮助都将不胜感激。谢谢。您正在写入字节和读取字符。使用
编写器
和读取器
,或者使用输出流
和输入流
EJP是正确的。更详细的解释是:字符有两个属性,您忽略了一个:编码
这意味着char myChar=158
分配myChar
Unicode代码点158(这不是Unicode中的可打印字符)
当您将其作为字节写入文件时(使用fileOut.write(int)
),您正在将Unicode字符转换为整数158
——编码丢失。write()
方法将从整数中除去除低8位以外的任何内容(write(158+256)
产生与write(158)
相同的结果)
当您再次读入数据时,您使用的是读取器
,它读取字节并将其转换为Unicode字符。要正确执行此操作,需要指定写入数据的编码。由于没有明确指定任何内容,Java使用平台默认编码(操作系统的默认编码)
因此读取器读取158
,并使用默认编码将其转换为char
要解决此问题,请始终使用
Reader
/Writer
以及InputStreamReader
和OutputStreamWriter
来指定要使用的编码UTF-8
是一个不错的选择,因为所有Java虚拟机都可以读取它们,并且所有Unicode字符都可以从此编码转换成/转换成字符。如果您只想写入/读取字符,请尝试和,但InputStreamRead/OutputStreamWriter更灵活