java - 将包含德语字符的 ANSI 文件转换为 UTF8

标签 java character-encoding

我从德国网站下载了一些纯文本文件,但我不确定编码是什么。文件中没有字节标记。我使用的解析器假设文件以 UTF8 编码,因此它无法正确处理某些重音字符(那些属于字节范围 > 127 的字符)

我想将其转换为 UTF8,但我不确定是否需要知道编码才能正确执行此操作。

其他人处理这些文件的方式是在 Windows 记事本中手动打开它并以 UTF8 重新保存。此过程保留了重音字符,因此如果可能的话,我希望自动执行此转换,而无需借助 Windows 记事本。

Windows 记事本如何知道如何正确地将其转换为 UTF8?
我应该如何将文件转换为 UTF8(在 Java 6 中)?

最佳答案

在 Java 7 中获取带有“Windows-1252”的文本,这是 Windows Latin-1。

Path oldPath = Paths.get("C:/Temp/old.txt");
Path newPath = Paths.get("C:/Temp/new.txt");
byte[] bytes = Files.readAllBytes(oldPath);
String content = "\uFEFF" + new String(bytes, "Windows-1252");
bytes = content.getBytes("UTF-8");
Files.write(newPath, bytes, StandardOption.WRITE);

这获取字节,将它们解释为 Windows Latin-1。 对于 NotePad 来说,诀窍是:NotePad 通过前面的 BOM 标记字符来识别编码。零宽度空格,通常在 UTF-8 中不使用。

然后从字符串中获取 UTF-8 编码。

Windows-1252 是 ISO-8859-1(纯 Latin-1),但有一些特殊字符,例如逗号引号,范围为 0x80 - 0xBF。

<小时/>

在 Java 6 中:

File oldPath = new File("C:/Temp/old.txt");
File newPath = new File("C:/Temp/new.txt");
long longLength = oldPath.length();
if (longLength > Integer.MAX_VALUE) {
    throw new IllegalArgumentException("File too large: " + oldPath.getPath());
}
int fileSize = (int)longLength;
byte[] bytes = new byte[fileSize];
InputStream in = new FileInputStream(oldPath);
int nread = in.read(bytes);
in.close();
assert nread == fileSize;

String content = "\uFEFF" + new String(bytes, "Windows-1252");
bytes = content.getBytes("UTF-8");

OutputStream out = new FileOutputStream(newPath);
out.write(bytes);
out.close();

关于java - 将包含德语字符的 ANSI 文件转换为 UTF8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18107209/

相关文章:

java - 过河者的一般 DFS

java - 原子计数器更新与阻塞队列的可见性和顺序

Java 字符串字符编码 - 法语 - 荷兰语语言环境

php - 发布PHP+MySQL网站时的Charset问题

javascript - 计算外语中出现的字符数

c++ - 与 C++ 中的字符不一致的算术?

php - 字符编码不匹配

java - Apache Camel RouteBuilder 配置方法

java - 切换菜单Java

java - 如何将文本文件中的行复制到 JComboBox 中?