写入文件时如何在Java中编码到Windows 1252?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18258355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to encode to windows 1252 in Java while writing to the file?
提问by Raghav
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?
如果我以windows-1252格式对数据进行编码并将其写入文件,如何在java中设置内容类型?
采纳答案by Sotirios Delimanolis
You can use an OutputStreamWriter
.
您可以使用一个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
).
使用典型Writer
方法将输出写入您的文件(或包装它,或将其声明为OutputStreamWriter
)。
The constructor also accepts a Charset
instead of the String
charset name. You can get it like so
构造函数还接受 aCharset
而不是String
字符集名称。你可以这样得到
Charset windows1252 = Charset.forName("windows-1252");
回答by Ted Hopp
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.
您需要指定编码。根据文档,你应该"Cp1252"
在使用java.io
和java.lang
类时使用,你应该在使用类"windows-1252"
时使用java.nio
。
So, for instance, you can do this:
因此,例如,您可以这样做:
File file = . . .;
Writer output = new PrintWriter(file, "Cp1252");
or, with java.nio
, this:
或者,使用java.nio
,这个:
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.)
(正如 Sotirios 在评论中指出的那样"windows-1252"
,无论文档怎么说,您都可以自始至终使用。)