Java如何向檔案中附加(寫入)字串?

2019-10-16 22:30:08

在java程式設計中,如何向現有檔案中附加(寫入)一個字串?

此範例顯示如何使用filewriter()方法在現有檔案中附加字串。

package com.yiibai;

import java.io.*;

public class AppendString2File {
    public static void main(String[] args) throws Exception {
        String filename = "write-filename.txt";
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(filename));
            out.write("This is the first String1\n");
            out.close();
            out = new BufferedWriter(new FileWriter(filename, true));
            out.write("This is the second String2\n");
            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);
        }
    }
}

執行上述範例程式碼,將產生以下結果 -

This is the first String1
This is the second String2

範例-2

以下是在java中向檔案中附加(寫入)字串的另一個範例。

package com.yiibai;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class AppendString2File2 {
     public static void main( String[] args ) { 
          try { 
             String data = " tw511.com is one of the best website in the world";
             File f1 = new File("F:/worksp/javaexamples/java_files/write-filename2.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