第14周作业
题目:
编写一个应用程序,输入一个目录和一个文件类型,显示该目录下符合该类型的所有文件。之后,将这些文件中的某一个文件剪切到另外一个目录中。
代码:
FileFilter类:
1 package 文件; 2 3 import java.io.File; 4 import java.io.FilenameFilter; 5 6 public class FileFilter implements FilenameFilter { 7 String type; 8 9 FileFilter(String type) { 10 this.type = type; 11 } 12 13 @Override 14 public boolean accept(File dir, String name) { 15 // TODO Auto-generated method stub 16 return name.endsWith(type); 17 } 18 19 }
FileOpt类:
1 package 文件; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.FileNotFoundException; 8 import java.io.FileOutputStream; 9 import java.io.IOException; 10 import java.io.OutputStream; 11 12 /** 13 * 包含两个方法一个是列出某个目录下的某个类型的文件,一个是剪切文件 14 * 15 */ 16 public class FileOpt { 17 String dir; 18 String type; 19 20 FileOpt(String dir, String type) { 21 this.dir = dir; 22 this.type = type; 23 } 24 25 public String[] List() { 26 File dir_list = new File(dir); 27 FileFilter filter = new FileFilter(type); 28 String fileList[] = dir_list.list(filter); 29 for (int i = 0; i < fileList.length; i++) { 30 System.out.println(fileList[i]); 31 } 32 return fileList; 33 } 34 35 public void cut(File f1, File f2) { 36 37 try { 38 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f1)); 39 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f2)); 40 41 int len = 0; 42 byte b[] = new byte[1024]; 43 while ((len = bis.read(b)) == -1) { 44 bos.write(b, 0, len); 45 46 } 47 bis.close(); 48 bos.close(); 49 } catch (FileNotFoundException e) { 50 e.printStackTrace(); 51 } catch (IOException e) { 52 // TODO Auto-generated catch block 53 e.printStackTrace(); 54 } 55 f1.delete(); 56 57 } 58 59 }
测试类:
1 package 文件; 2 3 import java.io.File; 4 import java.util.Scanner; 5 6 /** 7 * 测试,剪切、列出某个目录下的某个类型的文件 8 * 9 * 10 */ 11 public class Test { 12 public static void main(String[] args) { 13 String dir, type; 14 Scanner scan = new Scanner(System.in); 15 System.out.println("输入目录和类型:"); 16 dir = scan.next(); 17 type = scan.next(); 18 FileOpt f = new FileOpt(dir, type); 19 String nameList[] = f.List(); 20 System.out.println("输入要移动的目录:"); 21 String cutDir = scan.next(); 22 f.cut(new File(dir + "//" + nameList[0]), new File(cutDir + "//" + nameList[0])); 23 24 } 25 }