Java:字節流 文件輸出與讀入方法 并 實現文件拷貝
文章目錄
- 字符流
- FileReader
- FileWrite
字符流
字符流底層就是字節流。
字符流 = 字節流 + 字符集
特點:
輸入流:一次讀入一個字節,遇到中文時,一次讀多個字節。
輸出流:底層會把數據按照指定的編碼精選編碼, 變成漢字。
用于對應純文本操作。
FileReader
- 創建字符流對象
- 讀取數據
無參,返回int, 讀到末尾返回-1
有參,傳入char[],返回長度
默認也是一個一個字節讀,還換轉換成10進制返回
強轉為char即可 - 釋放資源
無參讀入:
package com.io.testdemo5;import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;public class Test5 {public static void main(String[] args) throws IOException {// 創建字符流對象FileReader fr = new FileReader("src\\ccc.txt");// 讀取數據int ch;while((ch = fr.read()) != -1) {System.out.print((char)ch);}// 釋放資源fr.close();}
}
傳入char[] 讀入:
package com.io.testdemo5;import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;public class Test5 {public static void main(String[] args) throws IOException {FileReader fr = new FileReader("src\\ccc.txt");char[] chars = new char[10];int len;while ((len = fr.read(chars)) != -1) {System.out.print(new String(chars, 0, len));}fr.close();}
}
其實是將轉十進制,強轉為char,放入數組中,這三步合并了。
FileWrite
- 創建對象,指定位置(產生數據傳輸通道)
參數可以是File對象,也可以是路徑 - 寫出數據
可以傳入字符數組,指定起始位置,長度
也可以傳入字符串
或者int十進制,會自動轉為字符 - 釋放資源
解除資源占用
package com.io.testdemo6;import java.io.FileWriter;
import java.io.IOException;public class Test7 {public static void main(String[] args) throws IOException {// true表示續寫FileWriter fw = new FileWriter("src/ccc.txt", true);// 傳入整數,字符串,字符數組都可以fw.write(25105); // 我fw.write('一');fw.write("你好阿\r\n");fw.write(new char[] {'a', 'b', 'c'});fw.close();}
}