【问题标题】:writing to a file in Java using printWriter by two ways, which one is better and why?通过两种方式使用 printWriter 在 Java 中写入文件,哪一种更好,为什么?
【发布时间】:2013-09-11 01:07:19
【问题描述】:

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

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

【问题讨论】:

  • 使用PrintWriter 遇到的一个问题是您必须手动刷新数据。

标签: java io filewriter printwriter bufferedwriter


【解决方案1】:

BufferedWriter

一般来说,Writer 会立即将其输出发送到底层 字符或字节流。除非需要立即输出,否则它是 建议在其 write() 的任何 Writer 周围包装一个 BufferedWriter 操作可能成本很高,例如 FileWriters 和 OutputStreamWriters。

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

【讨论】:

    【解决方案2】:

    您可以参考 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会更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-08
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      相关资源
      最近更新 更多