【问题标题】:How to write more than once to text file using PrintWriter如何使用 PrintWriter 多次写入文本文件
【发布时间】:2012-03-29 04:42:37
【问题描述】:

我知道如何创建PrintWriter,并且能够从我的 gui 中获取字符串并将其打印到文本文件中。

我希望能够采用相同的程序并打印到文件中,将文本添加到文件中,而不是替换文本文件中已有的所有内容。我将如何制作,以便在将更多数据添加到文本文件时,每次都将其打印在新行上?

任何示例或资源都会很棒。

【问题讨论】:

    标签: java text-files printwriter


    【解决方案1】:
        try 
        {
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
        out.println("the text");
        out.close();
         } catch (IOException e) {
        }
    

    FileWriter 构造函数的第二个参数将告诉它追加到文件(而不是清除文件)。

    对于昂贵的编写器(即FileWriter),建议使用BufferedWriter,使用PrintWriter 可以让您访问您可能习惯于从System.out 使用的println 语法。

    BufferedWriterPrintWriter 包装器并不是绝对必要的。

    【讨论】:

      【解决方案2】:
      PrintWriter writer=new PrintWriter(new FileWriter(new File("filename"),true));
      writer.println("abc");
      

      FileWriter 构造函数带有 append 属性,如果为 true 则可以追加到文件中。

      check this

      【讨论】:

        【解决方案3】:

        您的 PrintWriter 包装了另一个编写器,它可能是 FileWriter。当您构造该 FileWriter 时,请使用带有 File 对象和“附加”标志的构造函数。如果您将 true 作为附加标志传递,它将以附加模式打开文件,这意味着新输出将位于文件现有内容的末尾,而不是替换现有内容。

        【讨论】:

          猜你喜欢
          • 2016-10-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-14
          • 2017-08-22
          • 1970-01-01
          相关资源
          最近更新 更多