Java第14周作业

一、题目

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

二、代码

package mulu;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Scanner;

public class mulu {

    public static void main(String[] args) {
        System.out.println("输入一个目录");
        Scanner reader = new Scanner(System.in); 
        String s = reader.next();
        File dir = new File(s);                        
        System.out.println("输入文件类型");
        Scanner reader2 = new Scanner(System.in); 
        String k = reader2.next();
        FileAccept con = new FileAccept(k);
        String fileList[] = dir.list(con);
        System.out.println("目录下有"+fileList.length+"个文件");
        for(int i =0;i<fileList.length;i++) {
            System.out.println(fileList[i]);
        }        
        System.out.println("输入要剪切的文件");
        Scanner reader3 = new Scanner(System.in);        
        String g = reader3.next();    
        String f = s+"\\"+g;        
        File dir2 = new File(f);
        String FilePath = "E:\\txt"+"\\"+g;    
        try(BufferedReader in = new BufferedReader(new FileReader(f));
            BufferedWriter writer = new BufferedWriter(new FileWriter(FilePath));    
            ) {        
            String line = null;
            while((line=in.readLine())!=null) {
                System.out.println(line);
                writer.write(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        dir2.delete();                //删除文件
        
    }


}class FileAccept implements FilenameFilter{
    String type;
    FileAccept(String type){
        this.type = type;
    }
    public boolean accept(File dir, String name) {
        return name.endsWith(type);
    } 
}

 

三、运行结果

posted on 2019-12-08 22:57  心灵老鸭汤  阅读(175)  评论(0编辑  收藏  举报