JAVA高階基礎(30)---位元組輸入輸出流完成檔案複製
阿新 • • 發佈:2018-12-07
位元組輸入流
InputStream
注:更多方法請查詢API
package org.lanqiao.inputstream.demo; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class InputStreamDemo { public static void main(String[] args) { //建立讀取的目標檔案 File file = new File("test2.txt"); //建立輸入流 InputStream is = null; try { is = new FileInputStream(file); //建立一個位元組陣列 每次讀取位元組陣列長度的位元組 byte[] b = new byte[10]; int len = 0; while(( len = is.read(b)) != -1) { System.out.println("-------------"+b.length +"----"+len); for(int i = 0 ; i < len;i++) { System.out.println((char)b[i]); } System.out.println("========================"); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { if(is != null) { is.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //讀取檔案 每次讀取一個位元組 //System.out.println((char)is.read()); //System.out.println((char)is.read()); /*int i = 0 ; while((i = is.read()) != -1) { System.out.println((char)i); }*/ } }
在呼叫close方法時,都做了什麼事情?(為什麼要關閉?)
- 通知系統,該流物件變成垃圾
- 通知垃圾回收器來回收垃圾,釋放資源
在讀取檔案的時候:需要保證讀取的檔案一定要存在,如果不存在,則會出現 FileNotFoundException(編譯期異常)
在寫檔案的時候:檔案可以不存在
在建立輸出流物件時,系統都做了什麼事情?
- 呼叫系統資源,建立目標檔案(如果檔案不存在)
- 連結到目標資原始檔。
package org.lanqiao.filecopy.demo; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileCopyDemo { public static void main(String[] args) throws IOException { //建立讀取的目標檔案 File fileis = new File("test.txt"); //建立輸入流 InputStream is = new FileInputStream(fileis); //建立寫出的目標檔案 File fileos = new File("abc.txt"); //建立輸出流 OutputStream os = new FileOutputStream(fileos); //每次讀取一個位元組 /*int i = 0 ; while((i = is.read()) != -1) { os.write(i); } */ byte[] b = new byte[1024]; int len = 0;//每次讀取的位元組數 while((len = is.read(b)) != -1) { System.out.println(len); os.write(b,0,len); } } }