(Java) Java 讀寫txt 文件
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 getTxt {
static String filePath = "c://text.txt";
public getTxt() {
}
public static void main(String args[]) throws Exception {
try {
//寫入
writerTxt();
//讀取
readTxt();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
// 寫文件
private static void writerTxt() {
BufferedWriter fw = null;
try {
File file = new File(filePath);
fw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true), "UTF-8")); // 指點編碼格式,以免讀取時中文字符異常
fw.append("Hello World");
fw.newLine();
fw.append("Hello Java");
fw.flush(); // 全部寫入緩存中的內容
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 讀文件
private static void readTxt(QueryBean gqbnDAO) throws Exception {
//String filePath = WriterOrReaderTxt.class.getResource("").getPath().replace("file:", "") + "/test.txt"; // 文件和該類在同個目錄下
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"UTF-8")); //指定讀取文件編碼格式,以免出現中文亂碼
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();
}
}
}
}