Java如何寫入檔?

在java編程中,如何將內容寫入檔?

此示例顯示如何使用BufferedWriterwrite()方法來寫入檔。

package com.zaixian;

import java.io.*;

public class WriteToFile {
    public static void main(String[] args) {
        try {
            BufferedWriter out = new BufferedWriter(new FileWriter("outfilename.txt"));
            out.write("This a String write to file.\n");
            out.close();
            System.out.println("File created and write successfully");
        } catch (IOException e) {
        }
    }
}

執行上述示例代碼,將產生以下結果 -

File created and write successfully

示例-2

以下是寫入一個檔內容的另一個示例。

package com.zaixian;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile2 {
    public static void main(String[] args) {
        try {
            String content = "xuhuhu.com is one the best site in the world";
            File file = new File("outfile2.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();

            System.out.println("All Job Done!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意:上面代碼需要使用JDK7環境編譯後運行。

執行上述示例代碼,將產生以下結果 -

All Job Done!

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