我正在尝试将一个简单的字符写入文件并将其重新读入.将字符写入文件似乎工作正常(至少在十六进制编辑器中显示).当我将角色重新读回内存时,它完全是一个完全不同的价值.这是我的示例代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
}
我的问题是,这是怎么发生的?我想readChar等于我写的原始值(158),但我不确定我做错了什么.任何帮助,将不胜感激.谢谢.
| 归档时间: |
|
| 查看次数: |
396 次 |
| 最近记录: |