Java将文本附加到现有文件


Java将文本附加到现有文件

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;



public class AppendString {

   public static void main(String[] args) {

      StringBuilder sb = new StringBuilder();

      String str = "";

      try

      {

         String filename= "G:\\testfile.txt";

         FileWriter fw = new FileWriter(filename,true);



         //appends the string to the file

         fw.write("Java tutorials\n");

         fw.close();

         BufferedReader br = new BufferedReader(new FileReader("G:\\testfile.txt"));



         //read the file content

         while (str != null)

         {

            sb.append(str);

            sb.append(System.lineSeparator());

            str = br.readLine();

            System.out.println(str);

         }

         br.close();

      }

      catch(IOException ioe)

      {

         System.out.println(ioe);

      }

   }

}