0

I have a function that creates a file, but when I check the created file, its contents are not in utf-8, which causes problems with the contents in latin languages.

I thought that indicating the media type as html would be enough to keep formatting, but it did not work.

File file = new File("name of file");
        try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
            writer.write(contents);
            writer.flush();
            writer.close();

            MultipartFile multipartFileToSend = new MockMultipartFile("file", "name of file", MediaType.TEXT_HTML_VALUE, Files.readAllBytes(Paths.get(file.getPath())));

        } catch (IOException e) {
            e.printStackTrace();
        }

I'd like to know how to force this, because so far I have not figured out how.

Any tips?

Sabrina
  • 258
  • 1
  • 6
  • 20
  • nop, I'm not using BufferedReader reader – Sabrina Apr 26 '19 at 20:17
  • How do you verify that the contents is not in utf-8, and if it is not utf-8, what is it? Because your code as shown will write UTF-8 to `file`. – Mark Rotteveel Apr 27 '19 at 07:08
  • 1
    Possible duplicate of [Write a file in UTF-8 using FileWriter (Java)?](https://stackoverflow.com/questions/9852978/write-a-file-in-utf-8-using-filewriter-java) – Silvio Mayolo Apr 27 '19 at 20:38

1 Answers1

1

Instead of using FileWriter, create a FileOutputStream. You can then wrap this in an OutputStreamWriter, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:

try (OutputStreamWriter writer =
             new OutputStreamWriter(new FileOutputStream("your_file_name"), StandardCharsets.UTF_8))
    // do stuff
}