When I use "UTF-16" in an OutputStreamWriter, the content will be wrong.

I want to write into a txt file, so I make code as fellow:
FileOutputStream fos = new FileOutputStream("c:\\test.txt", true);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-16");
BufferedWriter bw = new BufferedWriter(osw);
bw.write("TEST 0 1 2 3 4 5 6 7 8 9...");
However, the String in test.txt is
? T E S T 0 1 2 3 4 5 6 7 8 9 . . .
There is a "?" in front of the String...
If I use "CP950" then the content will be correct.
How could I solve the problem?
Thanks.

The encoding in the constructor of OutputStreamWriter must be the one used when the file is read. If you are to read the text file with your default encoding on your OS, then you do not need to invoke the constructor OutputSreamWriter(OutputStream stream, String encodingName) with the double arguments but the constructor OutputStreamWriter(OutputStream stream) with the single argument. Or you can know the default encoding by System.getProperty("file.encoding") which returns a String object which shows your default (text file) encoding.

Similar Messages

Maybe you are looking for