使用printWriter以两种方式用Java写入文件,哪一个更好,为什么?

时间:2013-09-11 01:07:20

标签: java io filewriter printwriter bufferedwriter

我有以下创建和写入该文件的方法。

// Create the file and the PrintWriter that will write to the file

    private static PrintWriter createFile(String fileName){

        try{

            // Creates a File object that allows you to work with files on the hardrive

            File listOfNames = new File(fileName);


            PrintWriter infoToWrite = new PrintWriter(new BufferedWriter(
                    new FileWriter(listOfNames);
            return infoToWrite;
        }

        // You have to catch this when you call FileWriter

        catch(IOException e){

            System.out.println("An I/O Error Occurred");

            // Closes the program

            System.exit(0);

        }
        return null;

    }

该程序运行正常,即使我没有bufferedWriter and FileWriter如下所示。他们两个对象如何帮助改善写作过程?在这种情况下,我可以避免创建两个对象。

PrintWriter infoToWrite = new PrintWriter((listOfNames);

2 个答案:

答案 0 :(得分:0)

BufferedWriter

  

通常,Writer会立即将其输出发送到底层   字符或字节流。除非需要提示输出,否则它是   建议将BufferedWriter包装在任何write()的Writer周围   操作可能很昂贵,例如FileWriters和OutputStreamWriters。

     

如果你一次写大块文本(比如整行)   那么你可能不会注意到差异。如果你有很多代码   但是,一次追加一个字符,一个BufferedWriter   会更有效率。

答案 1 :(得分:0)

您可以参考API文档,您会发现不同之处:

BufferedWriter:Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. 

FileWriter:Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream. 

如果你想创建一个文件,FileWriter会更好。