PrintWriter追加至文本文件

来源:互联网 发布:php 腾讯云直播demo 编辑:程序博客网 时间:2024/05/17 02:47
  1. import java.util.*;
  2. import java.io.*;
  3. public class T {
  4.     public static void main(String[] args) {
  5.         String fileName = "data.txt";
  6.         FileWriter fw = null;
  7.         PrintWriter toFile = null;
  8.         try {
  9.             fw = new FileWriter(fileName, true); //  throw IOException
  10.             toFile = new PrintWriter(fw); // throw FileNotFoundException
  11.         } catch (FileNotFoundException e) {
  12.             System.out.println("PrintWriter error opening the file " + fileName);
  13.             System.exit(0);
  14.         } catch (IOException e) {
  15.             System.out.println("FileWriter error opening the file " + fileName);
  16.             System.exit(0); 
  17.         } 
  18.         System.out.println("Enter four lines of text:");
  19.         Scanner keyboard = new Scanner(System.in);
  20.         for (int count = 1; count <= 4; count++) {
  21.             String line = keyboard.nextLine();
  22.             toFile.println(count + " " + line);
  23.         } 
  24.         System.out.println("Four lines were written to " + fileName);
  25.         toFile.close();
  26.     }
  27. }