import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

 

public class WriterOrReaderTxt {

// 寫文件

private void writerTxt() {

BufferedWriter fw = null;

try {

File file = new File("D://text.txt");

fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8")); // 指定編碼格式,以免讀取時中文字符異常

fw.append("我寫入的內容");

fw.newLine();

fw.append("我又寫入的內容");

fw.flush(); // 全部寫入緩存中的內容

} catch (Exception e) {

e.printStackTrace();

} finally {

if (fw != null) {

try {

fw.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

 

// 讀文件

private void readTxt() {

String filePath = WriterOrReaderTxt.class.getResource("").getPath().replace("file:", "")

+ "/test.txt"; // 文件和該類在同個目錄下

BufferedReader reader = null;

try {

reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8")); // 指定讀取文件的編碼格式,要和寫入的格式一致,以免出現中文亂碼,

String str = null;

while ((str = reader.readLine()) != null) {

System.out.println(str);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

reader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}


From:ITEYE

arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()