Java File Writing Difference

Asked

Viewed 76 times

1

I would like to know the difference in these two methods of Writing in files.

Path path = Paths.get("E:/documentos/texte.txt");

Charset utf8 = StandardCharsets.UTF_8;

try(BufferedWriter escrever = Files.newBufferedWriter(path, utf8)) {
    escrever.write(" ");
} 

East:

File arq = new File("E:/documentos.texte.txt");
FileWriter fw = new FileWriter(arq);

try(BufferedWriter escrever = new BufferedWriter(fw)) {         
    escrever.write(" ");
}

2 answers

1

In a direct way, Path is more modern and does everything that File does in a better way. In new projects it is recommended to use Path.

For more information at that link.

0

I suggest using the first solution, it uses the newest file API, which has its advantages. For example it is more practical to work with Path than String for file paths.

Regarding the final result (the generated file) there is a difference between the two solutions: in the first solution UTF-8 is used, in the second the manufacturer of the FileWriter uses the encoding 'standard operating system (OS) which varies from OS to OS.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.