ファイルに単純な文字を書き込んで読み込もうとしています。ファイルに文字を書き込むことは、少なくとも表示されるヘキサエディタで)。私がキャラクターをメモリに読み込むと、そのキャラクターはまったく異なる値になります。ここに私の例のコードは次のとおりです。Java:ファイルへのcharの書き込み/読み込みで異なる結果が発生する
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)と等しくしたいと思いますが、私は何が間違っているのか分かりません。どんな助けもありがとう。ありがとう。