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

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

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

package com.zaixian;

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.zaixian;
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 = " xuhuhu.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

上一篇: Java檔 下一篇: Java目錄