我有一个创建文件的函数,但是当我检查创建的文件时,它的内容不是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();
}
我想知道如何强迫这个,因为到目前为止我还没有弄清楚如何。
有什么提示吗?
不使用 FileWriter
,创建一个FileOutputStream
。然后你可以把它包装在一个OutputStreamWriter
中,这允许你在构造函数中传递编码。然后,您可以将数据写入 try-with-resources 语句中:
try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream("your_file_name"), StandardCharsets.UTF_8))
// do stuff
}