字節流數據的寫出(輸出)和讀取(輸入)

寫出數據 FileOutputStream

FileOutputStream out = new FileOutputStream("E:\\a.txt");
//寫出字符串"abc"
//字節流沒有緩衝區
out.write("abc".getBytes());
//關流,釋放文件
out.close();

讀取數據 FileInputStream

import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamDemo {
    public static void main(String[] args) throws IOException {
  FileInputStream in = new FileInputStream("E:\\a.txt");
        //數據的讀取沒有緩衝區,須要手動提供一個緩衝區
     //設置爲每次存儲10個字符
        byte[] b = new byte[10];
        //定義一個變量用來記錄每次讀取到的字符個數,給變量len賦初值(能夠是任意值)
        //防止read讀取數據失敗致使報錯
        int len  = -1;
        //該read的返回值表示這一次讀取到的字符的個數
        while((len = in.read(b)) != -1){
            System.out.println(new String(b, 0, len));
        }
        in.close();
    }
}
相關文章
相關標籤/搜索