Java檔案(io)編程——檔案位元組流的使用

來源:互聯網
上載者:User

標籤:一個   示範   換行   存在   final   exce   檔案   finally   close   

案例1:

示範FileInputStream類的使用(用FileInputStream的對象把檔案讀入到記憶體)

首先要在E盤建立一個文字檔,命名為test.txt,輸入若干字元

 1 public class Demo_2 { 2  3     public static void main(String[] args) { 4         File f=new File("e:\\test.txt");            //得到一個檔案對象f,指向e:\\test.txt 5         FileInputStream fis=null; 6          7         try { 8             fis=new FileInputStream(f);             //因為File沒有讀寫的能力,所以需要使用FileInputStream 9 10             byte []bytes=new byte[1024];            //定義一個位元組數組,相當於緩衝11             int n=0;                                //得到實際讀取到的位元組數12             13             while((n=fis.read(bytes))!=-1){         //迴圈讀取14                 String s=new String(bytes,0,n);     //把位元組轉成String15                 System.out.println(s);16             }17             18         } catch (Exception e) {19             e.printStackTrace();20         }finally{                                   //關閉檔案流必須放在這裡21             try {22                 fis.close();23             } catch (IOException e) {24                 e.printStackTrace();25             }26         }27     }28 }

運行程式,控制台輸出test.txt中輸入的字元。

案例2:

示範FileOutputStream的使用(把輸入的字串儲存到檔案中)

 1 public class Demo_3 { 2  3     public static void main(String[] args) { 4  5         File f=new File("e:\\ss.txt"); 6         FileOutputStream fos=null;            //位元組輸出資料流 7          8         try { 9             fos=new FileOutputStream(f);10             11             String s="你好,瘋子!\r\n";      //\r\n為了實現換行儲存12             String s2="24個比利";13 14             fos.write(s.getBytes());15             fos.write(s2.getBytes());16         } catch (Exception e) {17             e.printStackTrace();18         }finally{19             try {20                 fos.close();21             } catch (IOException e) {22                 e.printStackTrace();23             }24         }25     }26 }

開啟E盤名為ss.txt的文字文件,存在輸入的字元。

 

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.