IO流之節點流
阿新 • • 發佈:2021-07-15
IO流
FileReader
-
read()的理解:返回讀入的一個字元。如果檔案到達末尾,返回-1
-
異常的處理:為了保證流資源一定可以執行關閉操作。需要使用try-catch-finally處理
-
讀入的檔案一定要存在,否則會報FileNotFoundException。
使用read()方法
package com.yicurtain.IO; import org.junit.Test; import java.io.File; import java.io.FileReader; import java.io.IOException; public class FileReadWriteTest { //將IOStream下的hello.txt檔案內容讀入程式中,並輸入在控制檯。 @Test public void test(){ // 1.例項化File類的物件,指明要操作的檔案 FileReader fr = null; try { File file = new File("hello.txt"); // 2. 提供具體的流 fr = new FileReader(file); // 3.資料的讀入 // read():返回讀入的一個字元。如果檔案到達末尾,返回-1 int data; while((data=fr.read())!=-1){ System.out.print((char)data); } } catch (IOException e) { e.printStackTrace(); } finally { // 4.流的關閉操作 try { if (fr!=null) fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
使用read(cbuf)的方法
@Test public void test2(){ FileReader fr = null; try { File file = new File("hello.txt"); // 2. 提供具體的流 fr = new FileReader(file); // 3.資料的讀入 // read(char[] cbuf):返回每次讀入cbuf陣列中字元的個數。如果檔案到達末尾,返回-1 char[] cbuf = new char[5]; int len; while((len=fr.read(cbuf))!=-1){ // 將字串cbuf轉換為string,從第0個位置,按長度為len的陣列往裡面填資料 String str = new String(cbuf,0,len); System.out.print(str); } } catch (IOException e) { e.printStackTrace(); } finally { // 4.流的關閉操作 try { if (fr!=null) fr.close(); } catch (IOException e) { e.printStackTrace(); } } }
FileWrite
- 輸出操作,對應的File可以不存在。並不會報異常
- File對應的硬碟中的檔案如果不存在,在輸出的過程中,會自動建立此檔案
- File對應的檔案如果存在
- 如果流使用的構造器是FileWrite(file)或FileWrite(file,false):對原有的檔案的覆蓋
- 如果流使用的構造器是FileWrite(file,true):不會對原有檔案覆蓋,而是對原有檔案追加內容
@Test public void test3() throws IOException { // 1.提供File類的物件,指明檔案路徑 File file = new File("hello1.txt"); // 2.提供FileWriter的物件,用於資料的寫出 FileWriter fr = new FileWriter(file); // 3.寫出的操作 fr.write("I have a dream!!\n"); fr.write("I also need to a dream!!"); // 4.流資源的關閉 fr.close(); }
檔案的複製操作
@Test
// 檔案的複製操作
public void test4(){
FileReader fr1 = null;
FileWriter fr2 = null;
try {
File file1 = new File("hello.txt");
File file2 = new File("hello2.txt");
fr1 = new FileReader(file1);
fr2 = new FileWriter(file2);
char[] cbuf = new char[5];
int len;
while ((len=fr1.read(cbuf))!=-1){
fr2.write(cbuf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fr1!=null)
fr1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fr2!=null)
fr2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileInputStream
同FileReader
FileOutputStream
同FileWrite
結論
- 對於文字檔案(.txt,.java,.c,.cpp),使用字元流(FileReader/FileWrite)處理
- 對於非文字檔案(.jpg,.mp3,.mp4,.doc),使用位元組流(FileInputString/FileOutputString)處理