返回顶部

收藏

java使用PrintWriter写文件

更多

下面示例代码演示使用PrintWriter方法写文件。

PrintWriter的构造函数接受FileWriter作为参数。得到PrintWriter实例之后调用其println()方法即可写入字符串。

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileUtil {

  public void writeLinesToFile(String filename,
                               String[] linesToWrite,
                               boolean appendToFile) {

    PrintWriter pw = null;

    try {

      if (appendToFile) {

        //If the file already exists, start writing at the end of it.
        pw = new PrintWriter(new FileWriter(filename, true));

      }
      else {

        pw = new PrintWriter(new FileWriter(filename));
        //this is equal to:
        //pw = new PrintWriter(new FileWriter(filename, false));

      }

      for (int i = 0; i < linesToWrite.length; i++) {

        pw.println(linesToWrite[i]);

      }
      pw.flush();

    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {

      //Close the PrintWriter
      if (pw != null)
        pw.close();

    }

  }

  public static void main(String[] args) {
    FileUtil util = new FileUtil();
    util.writeLinesToFile("myfile.txt", new String[] {"Line 1", 
                                                      "Line 2",
                                                      "Line 3"}, true);
  }
}

标签:java,IO,文件

收藏

0人收藏

支持

0

反对

0

发表评论