用InputStream和OutputStream將一個文件復制到另一個地方
阿新 • • 發佈:2019-03-24
pre 作用域 fileinput length test eno 文件 finally clas
1 import java.io.FileInputStream; 2 import java.io.FileNotFoundException; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 7 public class Test { 8 9 public static void main(String[] args) { 10 // 將一個文件復制到另一個地方 11 //先讀入再讀出 12 // 取貨員和送貨員一起工作 13 // 加大作用域 14 InputStream input = null; 15 FileOutputStream output = null; 16 try { 17 input = new FileInputStream("java.txt");// 18 output = new FileOutputStream("javacopy.txt"); 19 // 找一個筐筐 20 21byte[] ch = new byte[1024]; 22 // 把要的東西一個個放到筐筐裏 23 int length = 0; 24 // 取貨員把東西搬到一個筐筐裏 就走兩步把筐裏的東西一個個拿給送貨員 25 while ((length = input.read(ch)) != -1) { 26 output.write(ch); 27 28 } 29 } catch (FileNotFoundException e) {30 e.printStackTrace(); 31 } catch (IOException e) { 32 e.printStackTrace(); 33 } finally { 34 try { 35 output.close(); 36 } catch (IOException e) { 37 e.printStackTrace(); 38 } 39 try { 40 input.close(); 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 } 45 46 } 47 48 }
用InputStream和OutputStream將一個文件復制到另一個地方