题目:编写一个应用程序,输入一个目录和一个文件类型,显示该目录下符合该类型的所有文件。之后,将这些文件中的某一个文件剪切到另外一个目录中。
package com.huang; import java.util.*; import java.io.*; class FileAccept implements FilenameFilter{ String type; FileAccept(String type){ this.type = type; } public boolean accept(File Fname, String name) { return name.endsWith(type); } } public class Main { public static void main(String[] args) { System.out.println("请输入目录:"); Scanner q = new Scanner(System.in); String s = q.next(); File Fname = new File(s); System.out.println("请输入文件类型"); Scanner q1 = new Scanner(System.in); String p = q1.next(); FileAccept shu = new FileAccept(p); String fileList[] = Fname.list(shu); System.out.println(s+"目录下有"+fileList.length+"个文件"); for(int i =0;i<fileList.length;i++) { System.out.println(fileList[i]); } System.out.println("请输入要剪切的文件"); Scanner q2 = new Scanner(System.in); String G = q2.next(); String f = s+"\"+G; File Fname1 = new File(f); String FilePath = "D:\黄晓天\abc"+"\"+G; try(BufferedReader close1 = new BufferedReader(new FileReader(f)); BufferedWriter writer = new BufferedWriter(new FileWriter(FilePath)); ) { String line = null;//线程 while((line=close1.readLine())!=null) { System.out.println(line); writer.write(line); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } System.out.println("提示:被剪切的"+G+"文件"+"已经剪切完毕。"); Fname1.delete(); } }
运行截图: