Eu tenho um monte de arquivos .txt com alguns dados
1.txt
2.txt
3.txt
...
Eu quero adicionar o mesmo texto, por exemplo "hello world"
a cada arquivo txt a partir mesmo diretório.
Eu sei como trabalhar com um arquivo nesse caso, mas como lidar com vários arquivos? eu tenho que fazer isso usando Java ...
Você pode usar java.nio
junto com Java 8 recursos para listar os arquivos e executar alguma ação para cada um. Há um método para acrescentar texto para um arquivo.
Veja este exemplo e ler os poucos comentários no código, por favor:
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();
}
}
Infelizmente, a nested try
- catch
é devido necessária para o âmbito diferente do recurso de Java 8 forEach
. É feio, mas tem a vantagem de que você pode distinguir o Exception
s jogado tanto por listando os arquivos ou acessar um.
EDIT
Se você quiser adicionar uma nova primeira linha para o arquivo, então você terá que ler e re-gravar o arquivo. Veja este exemplo, que é apenas um pouco diferente da primeira:
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();
}
}
Outra diferença importante é a bandeira no
Files.write
, que não éAPPEND
mais, masTRUNCATE_EXISTING
porque você ler o arquivo em uma lista deString
representando as linhas, então você acrescentar que recolha ao que já contém a nova primeira linha. Depois, você acabou de escrever as linhas novamente, incluindo a nova primeira linha.