2008年4月25日 星期五

讀檔寫檔簡單測試

package com.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class filereaderTest {

public void filereaderTest(){

try {

FileReader fr =new FileReader("/Users/macbook/java/test.txt");
BufferedReader br= new BufferedReader (fr);

//從檔案輸入資料流入緩衝器類別物件br
String line;
while ((line =br.readLine())!=null) {
System.out.println(line);
}
System.out.println("========讀檔成功=========");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("========找不到檔案,讀檔失敗=========");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("========讀檔失敗=========");
}

}


public void filewritetest(){

BufferedWriter bw;
try {
bw = new BufferedWriter (
new FileWriter("/Users/macbook/java/test1.txt"));
//輸出資料流入緩衝器後再輸出到系統標準輸出
String s="字元輸出資料流BufferedWriter測試234!";
bw.write( s, 0, s.length( ) ); //用write方法將s輸出

bw.close();

System.out.println("========寫檔成功=========");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("========寫檔失敗=========");
}

}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new filereaderTest().filewritetest();

}

}

沒有留言: