標籤:main 存在 port io流 lib ace 理解 sys 另一個
Java的IO流分為字元流(Reader,Writer)和位元組流(InputStream,OutputStream),位元組流顧名思義位元組流就是將檔案的內容讀取到位元組數組,然後再輸出到另一個檔案中。而字元流操作的最小單位則是字元。可以先看一下IO流的概述:
下面首先是通過字元流對檔案進行讀取和寫入:
1 package lib; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileNotFoundException; 6 import java.io.FileReader; 7 import java.io.FileWriter; 8 import java.io.IOException; 9 import java.io.PrintWriter;10 11 public class Test {12 // 定義檔案路徑13 File f = new File("F:\\test.txt");14 //字元流寫入的方法15 public String writeInFile() throws IOException{16 String str = "";17 String count = "";18 try {19 // 使用字元流對檔案進行讀取20 BufferedReader bf = new BufferedReader(new FileReader(f));21 while (true) {22 //讀取每一行資料並將其賦值給str23 if ((count = bf.readLine()) != null) {24 str += count;25 } else {26 break;27 }28 }29 // 關閉流30 bf.close();31 } catch (FileNotFoundException e) {32 e.printStackTrace();33 }34 return str;35 }36 //字元流讀取的方法37 public void getReader(){38 try {39 //其中true表示在原本檔案內容的尾部添加,若不寫則表示清空檔案後再新增內容40 PrintWriter pw=new PrintWriter(new FileWriter(f,true));41 pw.write("測試輸入字串到檔案中2");42 pw.close();43 } catch (IOException e) {44 e.printStackTrace();45 }46 }47 public static void main(String[] args) throws IOException {48 Test test=new Test();49 //將字串輸入到檔案中50 test.getReader();51 //讀取相對應的字串52 String str=test.writeInFile();53 //將檔案中內容在控制台輸出54 System.out.println("檔案內容為:"+str);55 }56 }
上述代碼的關鍵地方都有注釋,就不再一一贅述了,主要就是在使用完流之後不要忘記關閉就好(行30,行42)
然後是通過位元組流的方式對檔案進行操作,將一個檔案中的內容複寫到另一個檔案中:
1 package com.file.test2; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 9 public class TestFile2 {10 //使用位元組流讀取並寫入檔案,將一個檔案複製到另一個檔案中11 public static void main(String[] args) throws IOException {12 //要複製的源檔案13 File f=new File("D:\\test.txt");14 //目標檔案15 File f2=new File("D:\\test2.txt");16 //定義一個byte類型的數組,用於儲存讀取到的內容17 byte [] b=new byte[1024];18 int length;19 try {20 //定義讀取的流21 FileInputStream in=new FileInputStream(f);22 //定義輸出到檔案的流23 FileOutputStream out=new FileOutputStream(f2);24 //將檔案內容輸出到另一個檔案中25 while((length=in.read(b))!=-1){26 out.write(b, 0, length);27 }28 out.close();29 in.close();30 } catch (FileNotFoundException e) {31 e.printStackTrace();32 }33 }34 }
在位元組流的操作中,第13行的源檔案必須存在,可以根據需要自行變更檔路徑,只需要存在即可,否則會報檔案找不到的錯誤,同時若想在控制台輸出讀取到的位元組流的內容則可以在第27和28行之間加兩句代碼:in.read(b, 0, b.length);System.out.println(new String(b));
以上就是字元流和位元組流的相關操作,其實代碼不難,主要是自己的理解,相同的問題每個人都會有不同的理解方式,當然,對於我們編程人員來說,除了要多思考之外還要多動手。最後希望以上內容能對大家有所協助
Java IO 位元組流與字元流 (三)