题目:编写一个应用程序,输入一个目录和一个文件类型,显示该目录下符合该类型的所有文件。之后,将这些文件中的某一个文件剪切到另外一个目录中。
代码:
package My; import java.util.*; import java.io.*; class FileAccept implements FilenameFilter{ String type; FileAccept(String type){ this.type = type; } public boolean accept(File dir, String name) { return name.endsWith(type); } } public class Test12_05 { public static void main(String[] args) { // TODO Auto-generated method stub 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 = "D:\Java.Test\新建文件夹"+"\"+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(); //删除文件 } }
运行结果:
剪切前:
剪切后原目录:
剪切后到目录: