11月4號
阿新 • • 發佈:2020-11-04
昨天上了一下午的Java課,主要學了Java的檔案流,包括檔案的一些操作,開啟檔案,讀寫檔案建立緩衝區等。
public static void main(String [] args) throws IOException{ //建立位元組輸入流 FileInputStream fis= new FileInputStream("FileInputStreamTest.java"); //建立一個長度為1024的竹筒 byte[] bbuf =new byte[1024]; //用於儲存實際讀取的位元組數 int hasRead=0; //使用迴圈來重複“取水”過程 while((hasRead =fis.read(bbuf))>0){ //取出“竹筒”中水滴(位元組),將位元組陣列轉換成字串輸入 System,out.println(bbuf,0,hasRead) } fis.close(); }
public static void main(String[] args) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; try { //建立位元組輸入流 fis = new FileInputStream("FileOutputStreamTest.java"); //建立位元組輸入流 fos = new FileOutputStream("newFile.txt"); byte[] bbuf = new byte[32]; int hasRead = 0; //迴圈從輸入流中取出資料 while ((hasRead = fis.read(bbuf)) > 0) { //每讀取一次,即寫入檔案輸出流,讀了多少,就寫多少。 fos.write(bbuf, 0, hasRead); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { //使用finally塊來關閉檔案輸入流 if (fis != null) { fis.close(); } //使用finally塊來關閉檔案輸出流 if (fos != null) { fos.close(); } } }