Java讀檔案和寫檔案
阿新 • • 發佈:2018-11-11
import java.io.*; public class FileTest { String path = "C:\\Users\\Desktop\\test.txt"; File f = new File(path); private void writeFile() throws IOException { //構建FileOutputStream物件,檔案不存在會自動新建 FileOutputStream fop = new FileOutputStream(f); // 構建OutputStreamWriter物件,引數可以指定編碼"UTF-8";不設定,預設為作業系統預設編碼; OutputStreamWriter writer = new OutputStreamWriter(fop, "UTF-8"); //寫入緩衝區 writer.append("該類用來建立一個檔案並向檔案中寫資料。\r\n如果該流在開啟檔案進行輸出前,目標檔案不存在,那麼該流會建立該檔案。\r\n"); writer.append("tvmain: [2102][ 3034.174501] DTL: recording: [recording.cpp 1355 readTSData()] res:0, available:872865792"); // 關閉寫入流,同時會把緩衝區內容寫入檔案 writer.close(); //關閉輸出流,釋放系統資源 fop.close(); } private void readFile()throws IOException { FileInputStream fip = new FileInputStream(f); InputStreamReader reader = new InputStreamReader(fip, "UTF-8"); StringBuffer sb = new StringBuffer(); while(reader.ready()){ //將讀取的資料轉化成char型別,加入StringBuffer物件sb裡 sb.append((char)reader.read()); } //將sb物件內容轉化成string型別,輸出 System.out.println(sb.toString()); //關閉讀取流 reader.close(); //關閉輸入流,釋放系統資源 fip.close(); } public static void main(String[] args)throws IOException { //建立物件 FileTest test = new FileTest(); //先把資料寫入檔案,後讀再讀取檔案,在控制檯輸出 test.writeFile(); test.readFile(); } }