java 怎么获取指定路径下的文件
发布网友
发布时间:2022-04-19 12:24
我来回答
共2个回答
热心网友
时间:2023-08-04 02:45
//根据你的要求修改了一下代码,现在已经能将某文件夹下的所有指定类型文件复制到
//指定文件夹下了
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class ReadFiles {
public static final String FILTER = "xml";
public static final String SRC_DIR = "E:\\StudyData";// 待扫描的文件夹
public static final String DES_DIR = "E:\\testdata";// 复制后的目标文件夹
public static void main(String[] args) {
long a = System.currentTimeMillis();
scanDir(SRC_DIR, DES_DIR);
System.out.println("共花费时间:"+(System.currentTimeMillis() - a)/1000+"秒");
}
public static void scanDir(String srcPath, String desPath) {
File dir = new File(srcPath);
File[] files = dir.listFiles();
if (files == null)
return;
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
scanDir(files[i].getAbsolutePath(), desPath);
} else {
String strFileName = files[i].getAbsolutePath().toLowerCase();
copyFile(strFileName, desPath + files[i].getName());
}
}
}
public static void copyFile(String srcName, String destName) {
if (srcName.endsWith(FILTER)) {
System.out.println("正在复制文件 "+srcName+" 至 "+destName);
try {
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(srcName));
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(destName));
int i = 0;
byte[] buffer = new byte[2048];
while ((i = in.read(buffer)) != -1) {
out.write(buffer, 0, i);
}
out.close();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
热心网友
时间:2023-08-04 02:45
new File("文件路径");