java第十四次作业

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

源码:

package cn.edu.ccut.po7;
import java.io.*;
import java.util.*;

class F implements FilenameFilter{
    String type;
     F(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) {
     Scanner reader=new Scanner(System.in);
      System.out.println("请输入路径:");
      String p=reader.nextLine();
      File file=new File(p);
      String filename[]=file.list();
     for(String name:filename){
        System.out.println(name);
       }
      System.out.println("输入查询的文件类型:");
       F filew = new F(reader.nextLine());
      String filename1[]=file.list(filew); 
    for(String name:filename1){
            System.out.println(name);
        }
             System.out.println("请输入剪切的文件名:");
             String cut = reader.nextLine();
            File cutfile = new File(p+"\\"+cut);
            System.out.println("请输入该文件需要移动到的目录:");
             String cutway = reader.nextLine(); 
            File cutlist = new File(cutway); 
            File newfile = new File(cutway+"\\"+cut);
             try {
               newfile.createNewFile();
           } catch (IOException e) {
                e.printStackTrace();
             }
             InputStream inputStream = null;
             BufferedInputStream bufferedInputStream = null;
            String filedata="";
            Writer writer = null;
             BufferedWriter bufferedWriter = null;
            try {
                 inputStream = new FileInputStream(cutfile);
               bufferedInputStream = new BufferedInputStream(inputStream);
                 byte[] b = new byte[1024];
               int count = 0;
                while((count = bufferedInputStream.read(b, 0, 1024))!=-1){
                   filedata=filedata+new String(b, 0, count);
               }
                 writer = new FileWriter(newfile);
               bufferedWriter = new BufferedWriter(writer);
                 bufferedWriter.write(filedata);
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
             } catch (IOException e) {
                 e.printStackTrace();
            }finally{
                 try {
                     bufferedInputStream.close();
                    inputStream.close();
                     bufferedWriter.close();
                    writer.close();
                } catch (IOException e) {
                 e.printStackTrace();
               }
             }
            cutfile.delete();
   }
} 

运行截图

剪切文件前原目录

剪切后对比图

posted @ 2019-12-06 21:50  长安别故里  阅读(177)  评论(0编辑  收藏  举报