话不多说,直接上代码
public class SearchJava {
public static void main(String[] args) {
String path = "E:\\STS_workplace\\tms"; // 要遍历的路径
try {
getFileList(path);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static List<File> getFileList(String strPath) throws FileNotFoundException {
List<File> filelist = new ArrayList<File>();
File dir = new File(strPath);
File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if (files[i].isDirectory()) { // 判断是文件还是文件夹
getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
} else if (fileName.endsWith("java")) { // 判断文件名是否以.java结尾
String strFileName = files[i].getAbsolutePath();
System.out.println("---" + strFileName);
String newfilePath = "E:\\STS_workplace\\myJava\\" + fileName;
copyFile(strFileName, newfilePath);
filelist.add(files[i]);
} else {
continue;
}
}
}
return filelist;
}
public static void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { // 文件存在时
InputStream inStream = new FileInputStream(oldPath); // 读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
}