在线程中进行读取并写入文件和wenjia

新人求(胸)罩!!!

 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 
 7 
 8 
 9 
10 public class work7 implements Runnable{
11     
12     /**
13      * @param args
14      * @throws IOException 
15      */
16     public static void main(String[] args) {
17         // TODO Auto-generated method stub
18 
19         work7 w = new work7();//创建接口类
20         Thread t = new Thread(w);//
21         t.start();//开启线程
22         
23         
24         
25         
26     }
27     
28     public static void Runt(File a,File b,String str){
29         
30         str = str +"\\"+ b.getName();//在此拼接文件的地址!供下次遍历的文件夹使用
31         
32         File[] k = b.listFiles();//获取当前文件中所以的文件
33         for(File file: k){//遍历
34             if(file.isDirectory()){//判断是文件夹?
35                 Runt(a,file,str);//递归调用此方法
36             }else if(file.isFile()){//判断是文件!
37                 try {//捕获异常
38                     FileInputStream in = new FileInputStream(file);//需要复制的文件
39                     File filF = new File(str);//创建该文件的父文件夹a.getAbsolutePath()+"\\"+file.getParentFile().getName()
40                     filF.mkdir();
41                     //输出文件的地址!
42                     FileOutputStream out = new FileOutputStream(new File(str+"\\"+file.getName()));
43                     byte[] by = new byte[1024];//创建缓存区
44                     try {
45                         while((in.read(by))!=-1){//读取时写入该文件中
46                             out.write(by);
47                         }
48                         
49                     } catch (IOException e) {
50                         // TODO Auto-generated catch block
51                         e.printStackTrace();
52                     }finally{
53                         try {//强制关闭资源
54                             out.close();
55                             in.close();
56                         } catch (IOException e) {
57                             // TODO Auto-generated catch block
58                             e.printStackTrace();
59                         }    
60                     }
61                 } catch (FileNotFoundException e) {
62                     // TODO Auto-generated catch block
63                     e.printStackTrace();
64                 }
65                 
66                 
67                 
68             }
69         }
70     }
71     
72 
73     @Override
74     public void run() {
75         File file = new File("C:\\Users\\wang\\Desktop\\IOTest");
76         
77         File file2 = new File("C:\\Users\\wang\\Desktop\\object");
78         Runt(file, file2,file.getAbsolutePath());
79     }
80 
81 }

一个简单读取写入就完成了!!!虽然有些麻烦!!!还有些繁琐!因为我还没有修改!!各位就先看着吧!!

posted @ 2016-12-06 09:50  涉世太浅  阅读(899)  评论(0编辑  收藏  举报