文章目錄
- 字節 流
- FileOutputStream
- 換行 與 續寫
- FileInputstream
- 實現 文件拷貝(字節數組 讀入方法)
- 字節流 編碼
字節 流
FileOutputStream
- 創建對象,指定位置(產生數據傳輸通道)
參數可以是File對象,也可以是路徑
如果文件不存在,且父級路徑正確,會新建文件
如果文件存在,會清空文件 - 寫出數據
ASCII對應 字符
可以傳入字節流,指定起始位置,長度 - 釋放資源
解除資源占用
package com.io.testdemo1;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class test1 {public static void main(String[] args) throws IOException {// 創建對象,指定位置(產生數據傳輸通道)FileOutputStream fos = new FileOutputStream("src/aaa.txt");// 寫入數據fos.write(97);byte[] bytes = {97, 98, 99, 100};fos.write(bytes);fos.write(bytes, 0, 2);// 釋放資源fos.close();}
}
換行 與 續寫
換行:
write(“\r\n”) 即可 linux只寫\n即可 mac寫\r
\r 表示回車 \n 表示換行
早期\r表示,回到此行開頭,\n才表示換行,一直沿用了下來。
續寫: 在輸出流對象的第二個參數中,加入true,表示打開續寫開關。
例子:
package com.io.testdemo1;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class test1 {public static void main(String[] args) throws IOException {FileOutputStream fos = new FileOutputStream("src/aaa.txt", true);// 寫入數據String str1 = "hello";byte[] bytes1 = str1.getBytes();fos.write(bytes1);// 寫入換行String str2 = "\r\n";byte[] bytes2 = str2.getBytes();fos.write(bytes2);fos.close();}
}
運行兩次的結果:
可以發現第二次續寫了,并沒有清空,同時換行了。
FileInputstream
與輸出相似。
- 創建對象(搭建橋梁)
如果文件不存在則直接報錯 - 讀入(返回值為int)
一次讀一個字節,ASCII對應的數字 (每次讀相當于一次指針的移動)
讀到末尾時返回-1 - 釋放資源
package com.io.testdemo2;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;public class test2 {public static void main(String[] args) throws IOException {// 創建對象FileInputStream fis = new FileInputStream("src/aaa.txt");// 循環 讀入int b; // 用變量去接收,要是條件和循環體內都read會跳兩次while ((b = fis.read()) != -1) {System.out.print((char)b);}// 釋放資源fis.close();}
}
運行結果與文件內容相同,說明成功讀取成功:
實現 文件拷貝(字節數組 讀入方法)
read可以傳入byte數組,這樣可以一次讀入一個字節數組大小,速度會快很多,大小最好為1024的整數倍。
注意:返回值變成了長度,讀完會返回-1。
將aaa.txt拷貝bbb.txt:
package com.io.copydemo;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class test3 {public static void main(String[] args) throws IOException {FileInputStream fis = new FileInputStream("src/aaa.txt");FileOutputStream fos = new FileOutputStream("src/bbb.txt");byte[] bytes = new byte[4096];int len;while ((len = fis.read(bytes)) != -1) {fos.write(bytes, 0, len);}fis.close();fos.close();}
}
運行結果:
字節流 編碼
最好不要用字節流取讀取文本文件。
編碼和解碼要統一。
idea默認utf-8,字母1字節,漢字3字節
eclipse默認jbk,字母1字節,漢字2字節
package com.io;import java.io.UnsupportedEncodingException;public class demo4 {public static void main(String[] args) throws UnsupportedEncodingException {String str = "abc你好";byte[] bytes = str.getBytes("GBK");String res1 = new String(bytes, "GBK");String res2 = new String(bytes, "UTF-8");System.out.println(res1); // abc你好System.out.println(res2); // abc���}
}