Java中的讀取與寫入檔案可以透過FileReader和FileWriter完成

讀取檔案(使用BufferedReader方便讀取整行)

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class test {
	public static void main(String [] argv) throws IOException {
		FileReader fr = new FileReader("FileName");
		BufferedReader br = new BufferedReader(fr);
		while (br.ready()) {
			System.out.println(br.readLine());
		}
		fr.close();
	}
}

寫入檔案

import java.io.FileWriter;
import java.io.IOException;
public class test {
    public static void main(String [] argv) throws IOException {
        FileWriter fw = new FileWriter("test.txt");
        fw.write("test");
        fw.flush();
        fw.close();
    }
}
Categories: Java