學習知識:輸入流和輸出流讀文件的簡單使用
test.txt:
iloveu是我愛你的意思。
Main.java
import java.io.*;public class Main {public static void main(String[] args) {// 1.利用輸入流讀文件//讀取test.txt并輸出文件內容try{FileInputStream inpt = new FileInputStream("D:\\LearnJAVA\\stream\\src\\test.txt");int b;System.out.println("利用FileInputStream.read()讀文件(獲取到的是字節流,有中文變成亂碼的問題):");while((b = inpt.read())!=-1){ //read讀取一個字符,返回為byteSystem.out.print((char)b); //利用強轉,轉為char輸出}System.out.println();} catch (FileNotFoundException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);} //FileInputStream等類有throws,要做好對應的異常捕獲。// 2.利用輸出流寫文件//讀取test.txt并輸出到testCopy.txt中try{FileOutputStream wf = new FileOutputStream("D:\\LearnJAVA\\stream\\src\\testCopy.txt");FileInputStream inpt = new FileInputStream("D:\\LearnJAVA\\stream\\src\\test.txt");int c = -1; //存儲讀取的字節數byte[] b= new byte[512]; //緩沖字節數組,一次讀到的字節會存進這個數組while ((c=inpt.read(b,0,512))!=-1){ //讀取512字節的數據,存入b數組wf.write(b,0,c); //將b數組里讀到的字節寫入輸出文件中}System.out.println("寫文件完成");} catch (FileNotFoundException e) {throw new RuntimeException(e);} catch (IOException e) {throw new RuntimeException(e);}}
}
輸出結果: