[英]How to append text to multiple files in one directory using Java
我有很多帶有一些數據的.txt文件
1.txt
2.txt
3.txt
...
我想向同一目錄中的每個txt文件添加相同的文本,例如"hello world"
。
我知道在這種情況下如何使用一個文件,但如何處理多個文件? 我必須使用Java來做到這一點......
您可以使用java.nio
和Java 8功能列出文件並為每個文件執行一些操作。 有一種方法可以將文本附加到文件中。
請參閱此示例並閱讀代碼中的一些注釋,請:
public static void main(String[] args) {
// define the directory that contains the text files
String dir = "U:\\workspace\\git\\ZZ--Temp\\TextFiles";
Path dirPath = Paths.get(dir);
// predefine some lines to be appended to every file
List<String> linesToBeAppended = new ArrayList<>();
linesToBeAppended.add("Hello new line in the file!");
try {
// go through all files in the directory (tested with .txt files only)
Files.list(dirPath)
// filter only files
.filter(Files::isRegularFile)
.forEach(filePath -> {
try {
// append the predefined text to the file
Files.write(filePath, linesToBeAppended, StandardOpenOption.APPEND);
} catch (IOException e) {
System.err.println("Could not append text to file "
+ filePath.toAbsolutePath().toString());
e.printStackTrace();
}
});
} catch (IOException e) {
System.err.println("Could not list files in "
+ dirPath.toAbsolutePath().toString());
e.printStackTrace();
}
}
不幸的是,由於Java 8功能forEach
范圍不同,嵌套的try
- catch
是必要的。 它很丑陋,但有一個優點,你可以通過列出文件或訪問文件來區分拋出的Exception
。
編輯
如果要向文件添加新的第一行,則必須讀取並重寫該文件。 看到這個例子,它與第一個例子略有不同:
public static void main(String[] args) {
// define the directory that contains the text files
String dir = "U:\\workspace\\git\\ZZ--Temp\\TextFiles";
Path dirPath = Paths.get(dir);
try {
// go through all files in the directory (tested with .txt files only)
Files.list(dirPath)
// filter only files
.filter(Files::isRegularFile)
.forEach(filePath -> {
// predefine some lines to be appended to every file
List<String> linesToBeAppended = new ArrayList<>();
// add the first line as predefined first line
linesToBeAppended.add("Hello another line in the file!");
try {
// then read the file and add its lines to the list with
// that already contains the new first line
linesToBeAppended.addAll(Files.readAllLines(filePath));
// append the extended text to the file (again),
// but this time overwrite the content
Files.write(filePath, linesToBeAppended,
StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException e) {
System.err.println("Could not append text to file "
+ filePath.toAbsolutePath().toString());
e.printStackTrace();
}
});
} catch (IOException e) {
System.err.println("Could not list files in "
+ dirPath.toAbsolutePath().toString());
e.printStackTrace();
}
}
另一個重要區別是
Files.write
的標志,它不再是APPEND
,而是TRUNCATE_EXISTING
因為您將文件讀入表示行的String
列表中,然后將該集合添加到已包含新第一行的集合中。 之后,您只需再次編寫行,包括新的第一行。
我想你想要做的是列出目錄中的所有文件,然后處理每個文件。 如果是這種情況你就可以做到
File[] children = dir.listFiles();
for (File child: children) {
if (child.isFile()) {
// append text
}
}
我已經省略了附加數據的代碼,因為你說你已經知道如何做到這一點。 此時,只需將該代碼應用於每個文件即可
您可以創建一個包含目錄的文件:
File directory = new File("pathOfYourDirectory");
然后,您可以獲得所有從屬文件和目錄:
File[] subDirectories = directory.listFiles();
現在你可以迭代這個數組了。 但是你應該檢查每個文件是否是一個文件。 然后,您可以獲取此文件並附加文本。
for (File subDir: subDirectories ) {
if (subDir.isFile()) {
// do your stuff
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.