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 }

猜你喜欢

转载自www.cnblogs.com/Satu/p/10012349.html