1. 程式人生 > >Java 把一個文字文件的內容複製到另一個文字文件

Java 把一個文字文件的內容複製到另一個文字文件

src.txt放在工程目錄下,dest.txt可建立,也可不建立。一旦執行程式,如果dest.txt不存在,將自行建立這個文字文件,再將src.txt中的內容複製到dest.txt

 

 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.FileNotFoundException;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.InputStream;
7 import java.io.OutputStream; 8 9 public class IOTest04 { 10 11 public static void main(String[] args) { 12 copy("src.txt", "dest.txt"); 13 } 14 15 public static void copy(String srcPath, String destPath) { 16 File src = new File(srcPath); 17 File dest = new
File(destPath); 18 InputStream is = null; 19 OutputStream os = null; 20 21 try { 22 is = new FileInputStream(src); 23 os = new FileOutputStream(dest, false); 24 25 byte[] buffer = new byte[1024 * 1]; //
1k bytes 26 int length = -1; 27 while ((length = is.read(buffer)) != -1) { 28 os.write(buffer, 0, length); 29 os.flush(); 30 } 31 } catch (FileNotFoundException e) { 32 e.printStackTrace(); 33 } catch (IOException e) { 34 e.printStackTrace(); 35 } finally { 36 try { 37 if (os != null) { 38 os.close(); 39 System.out.println("OutputStream Closed."); 40 } 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 try { 45 if (is != null) { 46 is.close(); 47 System.out.println("InputStream Closed."); 48 } 49 } catch (IOException e) { 50 e.printStackTrace(); 51 } 52 } 53 } 54 }