1. 程式人生 > >Java 檔案讀寫簡單例項

Java 檔案讀寫簡單例項

import java.io.*;

public class ReadWrite {

	public void writeFile() {
		String str = "this  is a program"; // 要寫入的內容
		try {
			FileOutputStream out = new FileOutputStream("d:/程式/ReadWriteshuchu.txt"); // 輸出檔案路徑
			out.write(str.getBytes());
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void readFile() {
		try {
			FileInputStream in = new FileInputStream("d:/程式/ceshi.txt"); // 讀取檔案路徑
			byte bs[] = new byte[in.available()];
			in.read(bs);
			System.out.println("file content=\n" + new String(bs));
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		ReadWrite t = new ReadWrite();
		t.readFile();
		t.writeFile();
	}
}