如何在现有文件中附加字符串?(How to append a string in an existing file?)

优质
小牛编辑
124浏览
2023-12-01

问题描述 (Problem Description)

如何在现有文件中附加字符串?

解决方案 (Solution)

此示例显示如何使用filewriter方法在现有文件中追加字符串。

import java.io.*;
public class Main {
   public static void main(String[] args) throws Exception {
      try {
         BufferedWriter out = new BufferedWriter(new FileWriter("filename"));
         out.write("aString1\n");
         out.close();
         out = new BufferedWriter(new FileWriter("filename",true));
         out.write("aString2");
         out.close();
         BufferedReader in = new BufferedReader(new FileReader("filename"));
         String str;
         while ((str = in.readLine()) != null) {
            System.out.println(str);
         }
      }
      in.close();
      catch (IOException e) {
         System.out.println("exception occoured"+ e);
      }
   }
}

结果 (Result)

上面的代码示例将产生以下结果。

aString1
aString2

以下是在java中的现有文件中追加字符串的示例

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class AppendToFileExample {
   public static void main( String[] args ) { 
      try { 
         String data = " xnip is a best website in the world";
         File f1 = new File("C:\\Users\\xnip7\\Desktop\\abc.txt");
         if(!f1.exists()) {
            f1.createNewFile();
         } 
         FileWriter fileWritter = new FileWriter(f1.getName(),true);
         BufferedWriter bw = new BufferedWriter(fileWritter);
         bw.write(data);
         bw.close();
         System.out.println("Done");
      } catch(IOException e){
         e.printStackTrace();
      }
   }
}

上面的代码示例将产生以下结果。

Done