java IO 學習(二)

來源:互聯網
上載者:User

標籤:輸入資料流   並且   puts   buffer   檔案的   gpo   輸出   write   reader   

檔案表示形式的轉換:

一、從系統檔案變成java中可以使用的檔案對象

  File file = new FIle("檔案的路徑");

二、讀取檔案系統中檔案的原始位元組流,要讀取字元流,請考慮使用 FileReader (File 轉 InputStream)

  FileInputStream fis = new FileInputStream(file);

三、建立一個檔案輸出資料流,用於寫入原始位元組流

  FileOutputStream fos = new FileOutputStream(file);

四、將一個輸入資料流其中的資料寫入到一個byte數組中(InputStream 轉 byte[])

  方法一:

  FileInputStream fis = new FileInputStream(file);

  ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

  byte[] buff = new byte[100]; //buff用於存放迴圈讀取的臨時資料 

  int rc = 0; 

  while ((rc = fis.read(buff, 0, 100)) > 0) { 

    baos.write(buff, 0, rc); 

  } 

  byte[] in_b = baos.toByteArray(); // in_b為轉換之後的結果 

  方法二:

  FileInputStream fis = new FileInputStream(file);

  byte[] buff = new byte[fis.available()]; 

  fis.read(buff);// read方法返回一個int值,並且把fis讀取到的資料儲存到buff數組中

  

五、byte[]轉換成InputStream

  ByteArrayInputStream bais = new ByteArrayInputStream(byte[] buf);

六、根據byte數組,組建檔案

  File file = new File(""); // 建立一個File

  OutputStream output = new FileOutputStream(file);// 轉成OutputStream 形式

  BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);// 轉成BufferedOutputStream 

  bufferedOutput.write(byt);// 把byte[]寫入BufferedOutputStream 

 

注意有些語句可能會拋出異常,注意流要記得關閉

  

 

java IO 學習(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.