【问题标题】:Read UTF-8 properties file and save as UTF-8 txt file读取 UTF-8 属性文件并保存为 UTF-8 txt 文件
【发布时间】:2020-06-09 09:34:17
【问题描述】:

我目前正在尝试分析我的所有属性文件,并且需要我的属性文件以 .txt 文件的形式作为一部分。问题是像 Ä,Ü,Ö 等德语“元音变音”没有被正确接管,因此我的程序不起作用。 (如果我手动将文件转换为 txt 没有问题,但整个事情应该动态运行)

这是我目前正在使用的代码:

private static void createTxt(String filePath, String savePath) throws IOException {
    final File file = new File(filePath);
    final BufferedReader bReader = new BufferedReader(new FileReader(file.getPath()));
    final List<String> stringList= new ArrayList<>();
    String line = bReader.readLine();
    while (line != null) {
      stringList.add(line);
      line = bReader.readLine();
    }
    final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(savePath), "UTF-8"));
    try {
      for (final String s : stringList) {
        out.write(s + "\n");
      }
    }
    finally {
      out.close();
    }
  }

txt 的编码也是 UTF-8 - 我认为问题是由于 bufferedReader 或缓存到 ArrayList 中

感谢您的时间和帮助, LG帕斯卡

【问题讨论】:

  • 请用英文写下您的问题
  • 对不起,我现在用英语表达了我的问题-感谢您的建议

标签: java writer


【解决方案1】:

在读取和写入文件时,您应该始终设置一个字符集。 FileReader 有一个采用 Charset 的构造函数。

new FileReader(file, StandardCharsets.UTF_8)

如果您只想读取文件中的所有行,只需使用 Files.readAllLines(path, StandardCharsets.UTF_8);

要写你可以使用Files.write(path, listOfStrings, StandardCharsets.UTF_8);

如果您只想复制文件,只需使用Files.copy(source, target);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2013-04-23
    相关资源
    最近更新 更多