'Found reliance on default encoding: new java.io.FileWriter(File, boolean)
I'm using FileWrite class to write into a file.and its working fine. But FindBugs is pointing me a Minor issue in my code snippet.
code snippet:
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();
}
}
}
Findbug Report:
Reliance on default encoding Found reliance on default encoding: new java.io.FileWriter(File, boolean)
In which line i'm getting this Error?
writer = new FileWriter(gpxfile, true);
Could some one please brief me what is this exactly? And how can we solve this?
Solution 1:[1]
Resolved this Issue by replacing
FileWriter writer = new FileWriter(gpxfile, true);
with
FileOutputStream fileStream = new FileOutputStream(gpxfile);
writer = new OutputStreamWriter(fileStream, "UTF-8");
Solution 2:[2]
File file = new File(someFilePath);
Writer w = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
PrintWriter pw = new PrintWriter(w);
pw.println(someContent);
pw.close();
Solution 3:[3]
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();
Solution 4:[4]
If you are using FileWriter
to write a file and you are worried about encoding.
You can change the code to use FileWriterWithEncoding where you can specify encoding.
With java 11 or above FileWriter comes with encoding to be used as an argument.
try (FileWriterWithEncoding fileWriter = new FileWriterWithEncoding(name, StandardCharsets.UTF_8,true)){
fileWriter.append("xxx");
....
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | kavie |
Solution 2 | Ramakrishna Tiruveedula Rohini |
Solution 3 | seaman29 |
Solution 4 | Vasily Kabunov |