If I were to encode the data in windows-1252 format and write it to the file, how to set the content type in java?
2 回答
You can use an OutputStreamWriter.
Writer out = new OutputStreamWriter(new FileOutputStream(yourFile), "windows-1252");
Use the typical Writer methods to write output to your File (or wrap it, or declare it as OutputStreamWriter).
The constructor also accepts a Charset instead of the String charset name. You can get it like so
Charset windows1252 = Charset.forName("windows-1252");
You need to specify the encoding. According to the documentation, you should use "Cp1252" when using java.io and java.lang classes and you should use "windows-1252" when using the java.nio classes.
So, for instance, you can do this:
File file = . . .;
Writer output = new PrintWriter(file, "Cp1252");
or, with java.nio, this:
File file = . . .;
Writer output = Files.newBufferedWriter(file.toPath(), "windows-1252");
(As Sotirios points out in a comment, you can probably use "windows-1252" throughout, despite what the docs say.)