如何在 java spring 中强制文件内容为 utf-8?
How to force content from a file to be utf-8 in java spring?
我有一个创建文件的功能,但是当我检查创建的文件时,它的内容不是 utf-8,这导致拉丁语言的内容出现问题。
我认为将媒体类型指定为 html 就足以保持格式化,但它不起作用。
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();
}
我想知道如何强制执行此操作,因为到目前为止我还没有弄清楚如何执行此操作。
有什么建议吗?
创建一个 FileOutputStream
,而不是使用 FileWriter
。然后,您可以将其包装在 OutputStreamWriter
中,这样您就可以在构造函数中传递编码。然后你可以将数据写入 try-with-resources Statement:
try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream("your_file_name"), StandardCharsets.UTF_8))
// do stuff
}
我有一个创建文件的功能,但是当我检查创建的文件时,它的内容不是 utf-8,这导致拉丁语言的内容出现问题。
我认为将媒体类型指定为 html 就足以保持格式化,但它不起作用。
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();
}
我想知道如何强制执行此操作,因为到目前为止我还没有弄清楚如何执行此操作。
有什么建议吗?
创建一个 FileOutputStream
,而不是使用 FileWriter
。然后,您可以将其包装在 OutputStreamWriter
中,这样您就可以在构造函数中传递编码。然后你可以将数据写入 try-with-resources Statement:
try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream("your_file_name"), StandardCharsets.UTF_8))
// do stuff
}