Java 14 周作业

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

代码:

package ccut.cn;
import java.util.*;
import java.io.*;
//F:\java
class c implements FilenameFilter{ //创建接口FilenameFilter使用类c
    String type;
    c(String type){
        this.type=type;
    }
    public boolean accept(File file,String name){
        return name.endsWith(type);
    }
}


public class Test {

    public static void main(String[] args) {
        System.out.println("请输入要查询的目录!");//查找全部文件
        Scanner r =new Scanner (System.in);
        String s=r.nextLine();
        File file =new File(s);
        String []a =file.list();
        for(String name:a ){
            System.out.println(name);
        }
        System.out.println("请输入文件类型!");//筛选指定类型文件
        String type= r.nextLine();
        FilenameFilter filter = new c(type);
        String []b =file.list(filter);
        for(String name:b ){
            System.out.println(name);
        }
        
        System.out.println("请输入想要移动文件名:");//移动文件
        String move=r.nextLine();
        File movefile=new File(file,move);
        
        System.out.println("请输入想要移动到的目录:");
        String place=r.nextLine();
        File placefile=new File(place,move);
        try {
            placefile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream in = null;
        BufferedInputStream bis = null;
        Writer w = null;
        BufferedWriter bw = null;
        try{
            in =new FileInputStream(movefile);
            bis= new BufferedInputStream(in);
            byte[]by=new byte[2048];
            int count =0;
            String string=""; //存原文件内容
            while((count =bis.read(by, 0, 2048))!=-1){
                string=string+new String(by);
                
                //System.out.println(new String(by));
                
            }
            w =new FileWriter(placefile,true); //true可见
            bw =new BufferedWriter(w);
            bw.write(string);//将内容写入到新的文件中
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally
        {
            try {
                bis.close();
                in.close();
                bw.close();
                w.close();  
            }
            catch(IOException e) {
                e.printStackTrace();
            }
        }
        
        movefile.delete();//删除原文件
        
    }

}

运行截图

 

 

 

posted @ 2019-12-07 21:10  shanshan3  阅读(266)  评论(0编辑  收藏  举报