12.3節 位元組流
位元組流可以處理各種對象
抽象基類:InputStream和OutputStream
讀取單個字元返回int類型:防止返回-1而終止
位元組流輸出:
int n=12;
byte arr[]={65,66,67,68};
//File輸出資料流 FileOutputStrea FileOutputStream fos=new FileOutputStream("res/data.txt");
fos.write(n);
fos.write(arr);
fos.write(arr,1,2);
fos.flush();
fos.close();
位元組流輸入:
FileInputStream fis=new FileInputStream("res/data.txt");
int m=fis.read();//一次讀一個
byte[] arr1=new byte[10];
int len=fis.read(arr1);//實際讀取的個數
System.out.println(m);
for(int i=0;i<len;i++){
System.out.println(arr1[i]);
}fis.close();
上面沒有判定是否讀到檔案末尾
Int n=0;
While(n=fis.read())!=-1{
}
檔案中還有多少個位元組可讀
fis.available();
System.out.println(fis.available());
還有多少可讀就讓數組多大
Byte[] arr=new Buty[fis.available()];
Fis.read(arr);
System.out.println(new String(arr));
複製---從源檔案中讀取資料寫到目標檔案中
輸入資料流—-FileInputStream 輸出資料流—FileOutputStream BufferedInputStream
FileInputStream fis=null;
FileOutputStream fos=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
Fis=new FileInputStream(“res/0.gif”);
Bis=new BufferedInputStream(fis);
Fos=new FileOutputStream(“res/1.gif”);
Bos=new BufferedOutputStream(fos);
Int n=0;
While((n=bis.read())!=-1){
Bos.write(n);
從鍵盤輸入
Int n=System.in.read();
System.out.println(n);
Byte arr[]=new Byte[10];
Int len=System.in.read(arr);//實際返回的字串
System.out.println(new String(arr,0,len));
把字元資料寫到磁碟檔案中
輸出資料流-----轉換流OutputStreamWriterr-----位元組流對象做參數---FileOutputStream
FileOutputStream fos=new FileOutputStream(“res/demo.txt”);
OutputStreamWriter osw=new OutputStreamWriter(fos,”UTF-8”);//UTF-8是指定的編碼方式【FileWriter fw=new FileWriter(“demo.txt”);】
Osw.write(“hello”);
Osw.write(“中國”);
Osw.close();
讀出【讀和寫的編碼方式應該相同,否則亂碼】
FileInputStream fis=new FileInputStream(“res/demo.txt”);
InputStreamReader isw=new InputStreamReader(fis);
Char cbuf[]=new char[10];
Int len=isw.read(cbuf);
System.out.println(new String(cubf,0,len));
如果使用指定編碼錶,必須使用轉換流。
將鍵盤錄入的資料存放區到一個檔案中
(1)資料來源 System.in
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
(2) 資料宿 檔案輸出 Writer FileWriter
FileWriter fw=new FileWriter(“demo.txt”);
BufferedWriter bw=new BufferedWriter(fw);
int c;
ch=br.read();
bw.writer(ch);
br.close();
bw.close();