查询一个文件下的所有同类型的文件
import java.io.File; import java.io.FileFilter; public class SearchFile { private static void searchFiles(File file,String str){ /*File[]fs =file.listFiles(new FileFilter() { @Override public boolean accept(File fileName) { // TODO Auto-generated method stub return fileName.getName().endsWith(str); } });*/ File[] fs = file.listFiles(); for(File f:fs){ if(f.getName().endsWith(str)) System.out.println(f.getName()); if(f.isDirectory()){ searchFiles(f, str); } } } public static void main(String[] args) { File file = new File("E:"); String str =".txt"; searchFiles(file, str); } }
复制一个文件夹下的所有文件
package ch0318hw; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; public class Copy { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入要复制的文件夹"); String str1 = sc.nextLine(); System.out.println("请输入要复制的地址"); String str2 = sc.nextLine(); File f1 = new File(str1); File f2 = new File(str2); copyDirectory(f1, f2); } private static void copyDirectory(File f1, File f2) { //System.out.println(f2.getAbsolutePath()); //System.out.println(f1.getName()); File fb=new File(f2.getAbsolutePath(),f1.getName()); if(!fb.exists()){ fb.mkdirs(); } File[] file = f1.listFiles(); for (File fa : file) { if (fa.isFile()) { //创建fa的名字.位置在f2 System.out.println(fb.getAbsolutePath()); System.out.println(fa.getName()); File fb1=new File(fb.getAbsolutePath(),fa.getName()); if(!fb1.exists()){ try { fb1.createNewFile(); FileInputStream fis = new FileInputStream(fa); FileOutputStream fos = new FileOutputStream(fb1); byte[]buf =new byte[(int) fa.length()]; fis.read(buf); fos.write(buf); fos.close(); fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if(fa.isDirectory()){ copyDirectory(fa, fb); } } } }