Search code examples
javaspringfileutf-8utf

How to force content from a file to be utf-8 in java spring?


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?


Solution

  • 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
    }