我正在使用FileWrite类写入文件。其工作正常。但是FindBugs在我的代码段中为我指出了一个小问题。
代码段:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";
FileWriter writer = null;
try {
File root = new File(Environment.getExternalStorageDirectory(), "Test");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, fileName);
writer = new FileWriter(gpxfile, true);
writer.append(text + "\n\n");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
发现错误的报告:
对默认编码的依赖 发现依赖默认编码:new java.io.FileWriter(File,boolean)
我在哪一行出现此错误?
writer = new FileWriter(gpxfile, true);
有人可以告诉我这到底是什么吗? 而我们该如何解决呢?
答案 0 :(得分:2)
通过替换来解决此问题
FileWriter writer = new FileWriter(gpxfile, true);
与
FileOutputStream fileStream = new FileOutputStream(gpxfile);
writer = new OutputStreamWriter(fileStream, "UTF-8");
答案 1 :(得分:0)
File file = new File(someFilePath);
Writer w = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
PrintWriter pw = new PrintWriter(w);
pw.println(someContent);
pw.close();
答案 2 :(得分:0)
import java.io.BufferedWriter;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
Charset charSet = Charset.forName("UTF-8");
File file = new File(someFilePath);
BufferedWriter bufferedWriter = Files.newBufferedWriter(file.toPath(), charSet);
bufferedWriter.write(header);
bufferedWriter.close();