標籤:一個 示範 換行 存在 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)編程——檔案位元組流的使用