I normally use PrintWritter object to create and write to a file, but not sure if its the best in terms of speed and security compare to other ways of creating and writing to a file using other approaches i.e.
Writer writer = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("example.html"), "utf-8"));
writer.write("Something");
vs
File file = new File("example.html");
BufferedWriter output = new BufferedWriter(new FileWriter(file));
output.write("Something");
vs
File file = new File("example.html");
FileOutputStream is = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("something");
vs
PrintWritter pw = new PrintWriter("example.html", "UTF-8");
pw.write("Something");
Also, when to use one over the other; a use case scenario would be appreciated. I'm not asking for how to create and write to file, I know how to do that. Its more of compare and contrast sort of question I'm asking.
解决方案
I prefer:
boolean append = true;
boolean autoFlush = true;
String charset = "UTF-8";
String filePath = "C:/foo.txt";
File file = new File(filePath);
if(!file.exists()) file.mkdirs();
FileOutputStream fos = new FileOutputStream(file, append);
OutputStreamWriter osw = new OutputStreamWriter(fos, charset);
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw, autoFlush);
pw.write("Some File Contents");
which gives you:
Decide whether to append to the text file or overwrite it.
Decide whether to make it auto-flush or not.
Specify the charset.
Make it buffered, which improves the streaming performance.
Convenient methods (such as println() and its overloaded ones).