星期二, 8月 29, 2006

java.io (3) - FileOutputStream & FileInputStream - 資料型態:byte - 寫入與讀取檔案內容

package ch12io;
import java.io.*;

public class FileOuput {
public static void main(String[] args) throws FileNotFoundException {//無檔案則丟出Exception
//寫入檔案(FileOutputStream)
FileOutputStream fos = null;
String s = "gecko";
byte[] data = null;
try {
fos = new FileOutputStream("test.txt", true);//true代表append資料至檔尾
data = s.getBytes(s);//由於資料型態為byte,所以須做轉換
fos.write(data);
} catch (IOException ex) {System.out.println("ex: "+ex); }
finally{
try {
fos.close();
} catch (IOException ex1) {System.out.println("ex1: "+ex1);}
}

//讀取檔案(FileInputStream)
FileInputStream fis = null;
fis = new FileInputStream("test.txt");
int totalbytes = 0;
try {
totalbytes = fis.available();
byte[] content = new byte[totalbytes];
if (fis.read(content) == totalbytes) {
String s1 = new String(content);
System.out.print(s1);
}
} catch (IOException ex2) {System.out.println("ex2: "+ex2);}
}
}

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁