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