星期二, 8月 29, 2006

java.io (4) - FileReader & FileWriter - 資料型態:character - 讀取與寫入檔案內容

package ch12io;
import java.io.*;

public class EX_FileWriter {
public static void main(String[] args) {
//寫入檔案
FileWriter fw = null;
String s = "gecko";
try {
fw = new FileWriter("test.txt", true);//true為可append新文字至test.txt尾端
fw.write(s);//完成寫入動作
} catch (IOException ex) {System.out.println("ex: "+ex);}
finally{
try {
fw.close();
} catch (IOException ex1) {System.out.println("ex1: "+ex1);}
}

//讀取檔案
FileReader fr = null;
char[] buffer1 = new char[1]; //一次讀取一個character,中文字與英文字符皆視為一個char
try {
fr = new FileReader("test.txt");//讀取檔案
while (fr.read(buffer1) != -1) { //-1表示資料尾端
String s1 = new String(buffer1); //將char轉換成String
System.out.print(s1);
}
} catch (IOException ex2) {System.out.println("ex2: "+ex2); }
}
}

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁