一、题目
编写一个应用程序,输入一个目录和一个文件类型,显示该目录下符合该类型的所有文件。之后,将这些文件中的某一个文件剪切到另外一个目录中。
二、代码
filee.java
package cn; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.Scanner; public class Filee { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.println("输入一个路径"); String path = reader.nextLine(); File file = new File(path); // FilenameFilter fn=new Way(rail); String[] filenames = file.list(); for (String name : filenames) { System.out.println(name); } System.out.println("输入查询后缀:"); String rail = reader.nextLine(); Way way = new Way(rail); String[] filenames2 = file.list(way);// 将查询后的文件名放入数组里 for (String name : filenames2) { System.out.println(name); } System.out.println("请输入需要剪切的文件名:"); String cutFileName = reader.nextLine(); File file2 = new File(path + "\" + cutFileName);// 存入原文件 System.out.println("请输入该文件需要移动到的目录:"); String cutFileWay = reader.nextLine(); File cutlist = new File(cutFileWay);// 存入目录 File newfile = new File(cutFileWay + "\" + cutFileName);// 存入新目录下新文件 try { newfile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } InputStream ins = null;// 声明 BufferedInputStream bins = null; Writer writer = null; BufferedWriter bw = null; String filedata = ""; try { ins = new FileInputStream(file2); bins = new BufferedInputStream(ins); byte[] b = new byte[1024]; int count = 0; try { while ((count = bins.read(b, 0, 1024)) != -1) { filedata = filedata + new String(b, 0, count);// 将字符串放入新文件 } writer = new FileWriter(newfile); bw = new BufferedWriter(writer); bw.write(filedata); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } try { bins.close(); ins.close(); bw.close(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } file2.delete(); } } class Way implements FilenameFilter { String type; Way(String type) { this.type = type; } public boolean accept(File dir, String name) { return name.endsWith(type); } }
三、运行结果