該解決方案的工作對我蠻好,請務必閱讀評論的細節:
public class FileCopy {
public static void recursivelyCopyContent(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
recursivelyCopyContent(fileEntry);
} else if (fileEntry.getName().substring(0, fileEntry.getName().lastIndexOf(".")).toLowerCase().equals(folder.getName().toLowerCase())) {
// just pass the folder and the file to the method that will do the actual content copy
copyContent(folder, fileEntry);
}
}
}
public static void copyContent(final File folder, final File fileName) {
try {
// get the byte[] content of the source file
byte[] fileContent = Files.readAllBytes(fileName.toPath());
for (final File fileEntry : folder.listFiles()) {
// only select files with a different absolute path than the source one
if(fileEntry.isFile() && !fileEntry.getAbsolutePath().equals(fileName.getAbsolutePath())) {
// append contents from source to destination file
Files.write(fileEntry.toPath(), fileContent, StandardOpenOption.APPEND);
}
}
}catch (IOException e) {
e.getStackTrace();
}
}
public static void main(String[] args) {
final File folder = new File("/path-of-directory/");
FileCopy.recursivelyCopyContent(folder);
}
}
只是要注意文件不帶擴展名:你的病情
fileEntry.getName().substring(0, fileEntry.getName().lastIndexOf(".")).toLowerCase().equals(folder.getName().toLowerCase())
將拋出java.lang.StringIndexOutOfBoundsException
因爲在他們的名字中不存在.
字符。
在這種情況下,我建議採取下列措施:
// both cases covered: files have or do not have an extension
if (
(!fileEntry.getName().contains(".") && fileEntry.getName().toLowerCase().equals(folder.getName().toLowerCase())) ||
(fileEntry.getName().contains(".") && fileEntry.getName().substring(0, fileEntry.getName().lastIndexOf(".")).toLowerCase().equals(folder.getName().toLowerCase()))
)
首先,你將不得不嘗試寫一些代碼,然後與我們分享,如果你遇到的具體問題。 – aUserHimself
final File folder = new File(「/ path-of-directory /」); 公共靜態無效listFilesForFolder(最終文件夾){ 的(最後文件FileEntry的:folder.listFiles()){ 如果(fileEntry.isDirectory()){ listFilesForFolder(FileEntry的); (0),fileEntry.getName()。lastIndexOf(「。」))。toLowerCase()。equals(folder.getName()。toLowerCase())) //發現文件內容必須是addes到同一目錄中的其他文件。如何? } } – Kyle
請編輯您的答案以更新它與任何額外的信息(如上面的代碼),不要忘記格式化它。 – aUserHimself