[英]Encoding cp-1252 as utf-8?
I am trying to write a Java app that will run on a linux server but that will process files generated on legacy Windows machines using cp-1252 as the character set. 我正在尝试编写一个Java应用程序,该应用程序将在linux服务器上运行,但将处理使用cp-1252作为字符集的旧Windows计算机上生成的文件。 Is there anyway to encode these files as utf-8 instead of the cp-1252 it is generated as?
无论如何,是否将这些文件编码为utf-8,而不是将其生成为cp-1252?
If the file names as well as content is a problem, the easiest way to solve the problem is setting the locale
on the Linux machine to something based on ISO-8859-1
rather than UTF-8
. 如果文件名和内容有问题,解决问题的最简单方法是将Linux计算机上的
locale
为基于ISO-8859-1
而不是UTF-8
。 You can use locale -a
to list available locales. 您可以使用
locale -a
列出可用的语言环境。 For example if you have en_US.iso88591
you could use: 例如,如果您有
en_US.iso88591
,则可以使用:
export LANG=en_US.iso88591
This way Java will use ISO-8859-1 for file names, which is probably good enough. 这样,Java将使用ISO-8859-1作为文件名,这可能已经足够了。 To run the Java program you still have to set the
file.encoding
system property: 要运行Java程序,您仍然必须设置
file.encoding
系统属性:
java -Dfile.encoding=cp1252 -cp foo.jar:bar.jar blablabla
If no ISO-8859-1 locale is available you can generate one with localedef
. 如果没有可用的ISO-8859-1语言环境,则可以使用
localedef
生成一个。 Installing it requires root access though. 但是安装它需要root访问。 In fact, you could generate a locale that uses CP-1252, if it is available on your system.
实际上,如果系统上可用,则可以生成使用CP-1252的语言环境。 For example:
例如:
sudo localedef -f CP1252 -i en_US en_US.cp1252
export LANG=en_US.cp1252
This way Java should use CP1252 by default for all I/O, including file names. 这样,Java默认应将CP1252用于所有I / O,包括文件名。
Expanded further here: http://jonisalonen.com/2012/java-and-file-names-with-invalid-characters/ 在此处进一步扩展: http : //jonisalonen.com/2012/java-and-file-names-with-invalid-characters/
You can read and write text data in any encoding that you wish. 您可以使用任何所需的编码来读取和写入文本数据。 Here's a quick code example:
这是一个快速的代码示例:
public static void main(String[] args) throws Exception
{
// List all supported encodings
for (String cs : Charset.availableCharsets().keySet())
System.out.println(cs);
File file = new File("SomeWindowsFile.txt");
StringBuilder builder = new StringBuilder();
// Construct a reader for a specific encoding
Reader reader = new InputStreamReader(new FileInputStream(file), "windows-1252");
while (reader.ready())
{
builder.append(reader.read());
}
reader.close();
String string = builder.toString();
// Construct a writer for a specific encoding
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF8");
writer.write(string);
writer.flush();
writer.close();
}
If this still 'chokes' on read, see if you can verify that the the original encoding is what you think it is. 如果在阅读时仍然“窒息”,请查看您是否可以验证原始编码是否符合您的想法。 In this case I've specified windows-1252, which is the java string for cp-1252.
在这种情况下,我指定了Windows-1252,这是cp-1252的java字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.