我的一些代码采用名为wonder1.txt
的文件,并将该文件中的日期写入另一个文件。假设我有更多文件,例如wonder2.txt
,wonder3.txt
,wonder4.txt
。如何在同一个文件中编写其余部分。
import java.io.*;
import java.util.*;
import java.lang.*;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "/Users/DAndre/Desktop/Alice/new1.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:2)
如果你有文件列表,那么你可以逐个循环它们。您当前的代码在循环内移动。 更简单的方法是将所有文件放在一个文件夹中并从中读取。
这样的事情:
File folder = new File("/Users/DAndre/Desktop/Alice");
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}