gpt4 book ai didi

java - 从多个文件中获取数据并移动到一个文件

转载 作者:行者123 更新时间:2023-12-02 05:17:09 25 4
gpt4 key购买 nike

我的一些代码采用名为 wonder1.txt 的文件并将该文件中的日期写入另一个文件。假设我有更多文件,例如 wonder2.txtwonder3.txtwonder4.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();
}
}
}

最佳答案

如果你有文件列表,那么你可以逐个循环它们。您当前的代码在循环内移动。更简单的方法是将所有文件放在一个文件夹中并从中读取。

类似这样的事情:

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();
}
}

关于java - 从多个文件中获取数据并移动到一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26826249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com