第14周作业

题目:

编写一个应用程序,输入一个目录和一个文件类型,显示该目录下符合该类型的所有文件。之后,将这些文件中的某一个文件剪切到另外一个目录中。

1.代码

 1 class FileAccept implements FilenameFilter{
 2 
 3     String s;
 4     FileAccept(String s){
 5         this.s=s;
 6     }
 7 
 8     public boolean accept(File dir, String name) {
 9         return name.endsWith(s);
10     }
11 }
12 public class lianxi1 {
13     public static void main(String[] args) throws IOException {
14         Scanner reader=new Scanner(System.in);
15         System.out.println("请输入要查询的目录!");
16         String dir=reader.nextLine();
17         File str=new File(dir);
18 
19         //筛选当前目录下,指定类型的文件
20 
21         System.out.println("请输入要筛选的文件类型:");
22         String type=reader.nextLine();//接收输入的文件类型
23         FileAccept accept=new FileAccept(type);
24         String fileList[]=str.list(accept);
25         for (int i = 0; i < fileList.length; i++) {
26             System.out.println(fileList[i]);
27         }
28         //剪切操作
29         System.out.println();
30         System.out.println("请输入需要剪切的文件名:");
31         String name=reader.nextLine();
32         File CutFile=new File(dir,name);//此对象是原目录下的原文件
33         System.out.println("请输入剪切到的目录:");
34         String NewPath=reader.nextLine();//接收新路径
35         File NewFile=new File(NewPath,name);//此对象是新目录下的同名新文件
36 
37         try {
38             NewFile.createNewFile();//通过方法,创建一个新的文件
39         } catch (IOException e) {
40             e.printStackTrace();
41         }
42 
43         BufferedInputStream bin=null;
44         BufferedWriter bw=null;
45         int count=0;
46         byte[]b=new byte[1024];
47         try {
48 
49             bin=new BufferedInputStream(new FileInputStream(CutFile));
50             String str2="";                                            //接收原文件中的数据
51             while((count=bin.read(b,0,1024))!=-1){
52                 str2=str2+new String(b);
53             }
54 
55             bw=new BufferedWriter(new FileWriter(NewFile,true));
56             bw.write(str2);//将接收的内容写入新文件中
57 
58         } catch (FileNotFoundException e) {
59             e.printStackTrace();
60         } catch (IOException e) {
61             e.printStackTrace();
62         }
63         finally{
64             bin.close();
65             bw.close();
66         }
67         CutFile.delete();//删除源文件
68 
69 
70     }
71 
72 }

2.运行结果

剪切前

剪切后

原文地址:https://www.cnblogs.com/changheng/p/12006730.html