简体   繁体   中英

Read UTF-8 properties file and save as UTF-8 txt file

I am currently trying to analyze all of my properties files and need my properties files in the form of a.txt file for one part. The problem is that german "Umlaute" like Ä,Ü,Ö etc. are not taken over correctly and therefore my program does not work. (If I convert the files manually into a txt there are no problems, but the whole thing should run dynamically)

Here is my code I am currently using:

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();
    }
  }

The encoding of the txt is also UTF-8 - I think the problem is due to the bufferedReader or caching into the ArrayList

Thank you for your time and help, LG Pascal

When reading and writing files you should always set a charset. FileReader has a constructor that takes a Charset.

new FileReader(file, StandardCharsets.UTF_8)

If you just want to read all lines from a file just use Files.readAllLines(path, StandardCharsets.UTF_8);

To write you can use Files.write(path, listOfStrings, StandardCharsets.UTF_8);

And if you only want to copy the files, just use Files.copy(source, target);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM