6

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?

Linus Fernandes
  • 498
  • 5
  • 30
kavie
  • 2,154
  • 4
  • 28
  • 53

4 Answers4

4

Resolved this Issue by replacing

FileWriter writer = new FileWriter(gpxfile, true);

with

  FileOutputStream fileStream = new FileOutputStream(gpxfile);
            writer = new OutputStreamWriter(fileStream, "UTF-8");
kavie
  • 2,154
  • 4
  • 28
  • 53
1
File file = new File(someFilePath);
Writer w = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
PrintWriter pw = new PrintWriter(w);
pw.println(someContent);
pw.close();
  • 3
    Welcome to StackOverflow. Can you please add some additional details to your answer? Although some code only answers are acceptable it is better to add an explanation for people who will read this in the future. – Simply Ged May 28 '19 at 22:12
1

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");
    ....
}
Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
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();
seaman29
  • 79
  • 1
  • 8