指定したディレクトリ内のすべての.javaファイルを別のディレクトリにコピーするプログラムを作成します。コピーが成功したら、.javaのサフィックス名を.txtに変更します。
public class Test1 {
private static String source = "C:\\aaa";
private static String target = "c:\\bbb";
public static void main(String[] args) throws Exception {
File f = new File(target);
if (!f.exists())
f.mkdirs();
f = new File(source);
copyJavaFile(f);
}
public static void copyJavaFile(File file) throws IOException {
if (file != null && file.exists()) {
if (file.isDirectory()) {
File[] fs = file.listFiles((dir, name) -> {
File temp = new File(dir, name);
if (temp.isFile())
return name.endsWith(".java");
return true;
});
if (fs != null && fs.length > 0) {
for (File temp : fs) {
copyJavaFile(temp);
}
}
} else if (file.isFile()) {
String path = file.getAbsolutePath();
String fileName=path.substring(path.lastIndexOf("\\"));
fileName=target+fileName;
try (Reader r = new FileReader(file);
Writer w = new FileWriter(fileName,true);) {
char[] arr = new char[8192];
int len = 0;
while ((len = r.read(arr)) > 0) {
w.write(arr, 0, len);
}
}
}
}
}
}