[英]rjb: Calling java methods from Ruby with compiled files in several directories
[英]Add text to several files in directories with conditions (Java)
我有一個包含一堆子目錄的目錄,每個子目錄都包含幾個文本文件。 每個子目錄都包含一個與包含它的子目錄同名的文本文件; 我想將此文件的內容添加到所有其他文本文件中,但與子目錄共享名稱的文件除外,並且我想在 java 中創建它。
例如給定目錄“a”,包含子目錄“b”、“c”、“d”,分別包含文件“b”、“e”、“f”和“c”、“g”、“h” ,和“d”、“i”、“j”,我想讓目錄“a”包含子目錄“b”、“c”、“d”,分別包含文件“b”、“b+e”、“ b+f", and "c", "c+g", "c+h", and "d", "d+i", "d+j", 並可能刪除添加的文件,即文件“a”、“b”、“c”。
final File folder = new File("/path-of-directory/");
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else if (fileEntry.getName().substring(0, fileEntry.getName().lastIndexOf(".")).toLowerCase().equals(folder.getName().toLowerCase()))
// found the file which content has to be added to other files in the same directory. How to?
}
}
這個解決方案對我來說很好用,請務必閱讀評論以獲取詳細信息:
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()))
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.