FileInputStream讀取檔案&FileOutputStream寫入檔案
阿新 • • 發佈:2018-11-16
FileInputStream讀取檔案&FileOutputStream寫入檔案
概念摘自:http://jingyan.baidu.com/article/5552ef473ab5f2518ffbc98e.html
Java的流式輸入輸出建立在4個抽象類的基礎上:InputStream,OutputStream,Reader和Writer。它們用來建立具體的流式子類。InputStream和OutputStream類被設計為位元組類,而Reader和Writer被設計為字元流類。
一般,處理字元和字串用字元流類,位元組和二進位制檔案用位元組類。本篇只講位元組流類;
位元組流中的兩個頂層類為:InputStream(輸入位元組流)和OutputStream(輸出位元組流). 其下有兩個子類FileInputStream(檔案輸入流)和FileOutputStream(檔案輸出流)。
FileInputStream讀取的兩種方法:逐位元組讀;以位元組陣列讀取兩種方式;
public static void main(String[] args) { //建立檔案物件,指定要讀取的檔案路徑(要讀的檔案一定要存在) File file=new File("E:\\a.text"); try { //建立檔案輸入流物件.指定要讀取的檔案物件 FileInputStream fin=new FileInputStream(file); /***********方法一(將輸入流的資料傳遞給位元組陣列)*********/ //建立位元組陣列,準備將檔案流中的資料傳給位元組陣列 /*byte[] b=new byte[fin.available()]; //將位元組流中的資料傳遞給位元組陣列 fin.read(b); //將位元組陣列轉為字串 String s=new String(b); System.out.println(s);*/ /*********************************************/ /********方法二(逐位元組讀取資料從位元組輸入流)***********/ int l; while ((l=fin.read())!=-1) { System.out.println((char)l); //測試read()方法的含義,什麼是逐位元組讀,及int型別的l代表什麼意思,測試結果l代表儲存的內容的int的表現形式,與進位制相關,不做深究 //System.out.println((char)l+"\t"+l); } fin.close(); /************************************************/ } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
FileOutputStream寫入檔案的兩種方式:以位元組陣列寫入;逐位元組寫入;
public static void main(String[] args) { // TODO Auto-generated method stub //建立檔案物件,指定要寫出的檔案路徑 File file=new File("d:\\d.text"); try { //建立檔案位元組輸出流物件,準備向d.txt檔案中寫出資料,true表示在原有的基礎上增加內容 FileOutputStream fout=new FileOutputStream(file,true); Scanner sc=new Scanner(System.in); System.out.println("請寫出一段字串:"); String msg=sc.next()+"\r\n";; /******************(方法一)按位元組陣列寫入**********************/ //byte[] bytes = msg.getBytes();//msg.getBytes()將字串轉為位元組陣列 //fout.write(bytes);//使用位元組陣列輸出到檔案 /******************(方法一)逐位元組寫入**********************/ byte[] bytes = msg.getBytes(); for (int i = 0; i < bytes.length; i++) { fout.write(bytes[i]);//逐位元組寫檔案 } fout.flush();//強制重新整理輸出流 fout.close();//關閉輸出流 System.out.println("寫入完成!"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
位元組流轉化為字元流
//建立位元組輸出流物件 FileOutputStream fout=new FileOutputStream(new File("student.xml")); //建立位元組流緩衝區,加快寫出速度 BufferedOutputStream bout=new BufferedOutputStream(fout); //建立字元輸出流物件 BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(bout, "utf-8")); doc.write(bw); bw.flush(); bw.close();
為什麼將位元組流轉化為字元流?
因為位元組流是二進位制讀寫的,在外部開啟是亂碼,轉化為字串或字元可以讓檔案在外部也可以看到內容!根據具體的需求確定用哪個!
標籤: