找出d盘下所有的 .java 文件,拷贝至 c:\jad 目录下,并将所有文件的类型由.java 修 改为.jad
高手指点那..急
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/*
找出d盘下所有的 .java 文件,拷贝至 c:\jad 目录下,并将所有文件的类型由.java 修
改为.jad 。
*/
public class CopyFile {
public static void main(String[] args) throws IOException {
File fromPath = new File("D:");
File toPath = new File("c:\\jad");
checkFiles(fromPath, toPath);
}
private static void checkFiles(File fromPath, File toPath)
throws IOException {
if (!fromPath.exists()) {// 测试此抽象路径名表示的文件或目录是否存在
throw new RuntimeException("文件不存在,请重新输入!");
} else if (fromPath.isFile() && fromPath.getName().endsWith(".java")) {
copyFiles(fromPath, toPath);
} else {
File[] files = fromPath.listFiles();
for (File file : files) {// 对数组进行遍历
if (file.isDirectory()) {//这句话是什么意思?
checkFiles(file, toPath);
} else if (file.getName().endsWith(".java")) {
copyFiles(file, toPath);
}
}
}
}
private static void copyFiles(File cFile, File pFile) throws IOException {
//这里边写乱了,不知道怎么把文件和名字复制到c:\\jab中了
String newfileName = cFile.getName();
FileInputStream fis = new FileInputStream(newfileName);
FileInputStream fisf = new FileInputStream(cFile);
FileOutputStream fos = new FileOutputStream(pFile.createTempFile(
newfileName, ".java"));
byte[] b = new byte[1024];
int ch = 0;
while (-1 != (ch = fisf.read())) {
fos.write(ch);
System.out.print(ch);
}
fis.close();
fos.close();
}
}
[解决办法]
if (file.isDirectory()) { // 如果该文件对象是一个目录
checkFiles(file, toPath); // 递归调用,实现对目录的穷举
} else if (file.getName().endsWith(".java")) { // 如果该文件名以.java结尾
copyFiles(file, toPath); // 复制该文件
}
复制文件的函数这里:
FileInputStream fis = new FileInputStream(newfileName);
这句话是多余的。
就是读取cFile文件的内容,写入pFile目录下的同名文件中,你的命名给的不好,所以看起来很混乱。
- Java code
private static void copyFiles(File cFile, File toDir) throws IOException { String fileName = cFile.getName(); FileInputStream fis = new FileInputStream(cFile); FileOutputStream fos = new FileOutputStream(new File(toDir, fileName)); try { byte[] b = new byte[8192]; // 缓冲区可以设置大点 int ch = 0; while (-1 != (ch = fisf.read(b))) { fos.write(b, 0, ch); } } finally { fos.close(); fis.close(); } }