0

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

// 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);
4

2 回答 2

0

缓冲写入器

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

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

于 2013-09-11T01:15:09.823 回答
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 会更好。

于 2013-09-11T01:18:16.113 回答