package uu; import java.io.*; public class FileAccept implements FilenameFilter { String str=null; FileAccept(String s){ str=""+s; } public boolean accept(File dir,String name) { return name.endsWith(str); } public static void main(String[] args) { File dir=new File("D:\\rm"); FileAccept acceptCondition=new FileAccept("txt"); // String fileList[]=dir.list(acceptCondition); System.out.println("目录下有"+fileList.length+"个文件"); for(int i=0;i<fileList.length;i++) { System.out.println(fileList[i]); }
二、运行结果
之后,将这些文件中的某一个文件剪切到另外一个目录中。
三、程序
File file1=new File("D:\\rm\\haha.txt"); File file2=new File("C:\\Drivers\\rm\\haha.txt"); file1.deleteOnExit(); //在程序结束是删除原来的文件1 try { file2.createNewFile(); //在C盘创建新的文件2 }catch (IOException e) { e.printStackTrace(); } cutFile(file1,file2); } public static void cutFile(File file1,File file2) { FileOutputStream fileOutputStream=null; InputStream inputStream=null; byte[] bytes=new byte[1024]; int temp=0; try { inputStream=new FileInputStream(file1); fileOutputStream=new FileOutputStream(file2); while((temp=inputStream.read(bytes))!=-1) { fileOutputStream.write(bytes,0,temp); fileOutputStream.flush(); } }catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }finally { if(inputStream!=null) { try { inputStream.close(); }catch (IOException e) { e.printStackTrace(); } } if(fileOutputStream!=null) { try { fileOutputStream.close(); }catch (IOException e) { e.printStackTrace(); } } } } }
四、运行结果