Ref: should I use PrintWriter to wrap BufferedWriter?
The main reason for using PrintWriter is the wealth of convenience functions which do intelligent output of various things. If you don't need that capability, you wouldn't use a PrintWriter at all.The point of a BufferedWriter is to allow output to be buffered and then written in a batch.If you batch I/O to and from external devices, you can really reduce the overall cost because output (or input) can be batched--and you end up waiting for completion just once per batch, rather than once per I/O operation.
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.FileWriter;
import java.io.File;
class Printer {
public static void write(String path, String contents) throws IOException {
PrintWriter pw = new PrintWriter(new FileWriter(new File(path)));
pw.print(contents);
pw.close();
}
} class Buffered {
public static void write(String path, String contents) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(path)));
bw.write(contents);
bw.close();
}
}
User.java 文件是测试类,将内容写入文件中,
import java.io.IOException;
class User{
public static void main(String[] args){
StringBuffer sb = new StringBuffer();
for(int i = ; i < ; i++)
sb.append("telerikkjuatlistenedk76914761ilovemyprofessionaljob.").append("\n");
try{
long startTime = System.nanoTime();
// Printer.write("H:\\OwnTool\\WriterDataToText\\out.txt",sb.toString());
Buffered.write("H:\\OwnTool\\WriterDataToText\\out.txt",sb.toString());
long endTime = System.nanoTime();
System.out.println("cost '" + (endTime - startTime) + "' ns ");
}catch(IOException e){
e.printStackTrace();
}
}
}
多次试验都得到差不多的结果,BufferedWriter花的时间会比 PrintWriter '少'很多:
对于 BufferedWriter 的输出结果:
cost '72761343' ns
对于 PrintWriter 的输出结果:
cost '95209656' ns
/*
author:kju
create a class that write string content to a specified path.
*/
package kju.write; import java.io.PrintWriter;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.FileWriter;
import kju.print.Printer;
public class Writer
{
public static void PrintWrite(String path, String content) throws IOException {
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(path)));
pw.write(content);
pw.close();
}
public static void BufferedWrite(String path, String content) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
bw.write(content);
bw.close();
}
public static void main(String[] args)
{
String s = "";
String path = "D:\\out.txt";
for (int i = 0; i < 10000; i++)
{
s += "kjuatlistened";
}
try
{
long start = System.nanoTime();
//PrintWrite(path,s);
BufferedWrite(path,s);
long end = System.nanoTime();
Printer.println("done,elapse " + (end - start) + " s");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}
the comparation is result shown with a screenshot: