1

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?

4

2 回答 2

9

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");
于 2013-08-15T17:40:11.077 回答
4

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.)

于 2013-08-15T17:41:19.337 回答