迟到的第14周作业

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

代码

1.FA.java

 

/**
 * 包含成员变量 str、构造方法、accept方法
 */
import java.io.File;
import java.io.FilenameFilter;
	class FA implements FilenameFilter{
		String str = null;

		public FA(String s) {
			str = "."+s;
		}
		public boolean accept(File dir, String name) {
			// TODO Auto-generated method stub
			return name.endsWith(str);
		}
	}

 

2.Test.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class Test {
 public static void main(String[] args)  {
  Scanner reader=new Scanner(System.in);
        System.out.println("请输入目录:");
        String Path =reader.nextLine();
        File dir = new File(Path);  //输入文件路径
        System.out.println("请输入该目录下要求的文件类型");
        String rear =reader.nextLine();
        FA acceptCondition = new  FA(rear);//设置文件名后缀
        String fileList[] =dir.list(acceptCondition);   //获取文件名
   System.out.println("目录下有"+fileList.length+"文件");
  for (int i = 0; i < fileList.length; i++) {
   System.out.println(fileList[i]);
  }
  System.out.println("请输入需要剪切的文件名:");
        String name = reader.nextLine();
        System.out.println("请输入需要剪切至那个目录");
        String target = reader.nextLine();
        File namefile = new File(Path+"\\"+name);
        FileInputStream in = null;
  try {
   in = new FileInputStream(namefile);
  } catch (FileNotFoundException e2) {
   // TODO Auto-generated catch block
   e2.printStackTrace();
  }   
        File targetfile = new File(target+"\\"+name);
        try {
   targetfile.createNewFile();
  } catch (IOException e1) {
  
   e1.printStackTrace();
  }           //在目标目录创建新文件;
        FileOutputStream out = null;
  try {
   out = new FileOutputStream(targetfile);
  } catch (FileNotFoundException e1) {
   e1.printStackTrace();
  }
        byte[] bytes = new byte[1024];
        int count = 0 ;
        try {
            while((count = in.read(bytes, 0, 1024)) != -1){    //将原文件内容读写入到目标文件中
                out.write(bytes, 0, count);
                out.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }finally{           
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        namefile.delete(); //删除原文件
    }
 }

运行结果

 

 

 

 

 

 

posted @ 2019-12-07 11:25  朱佳美20194662  阅读(108)  评论(0编辑  收藏  举报