以下是一个示例的 Java 代码,用于读取一周内不同日期下的文件夹内的 TXT 数据文件,并将数据文件进行合并,将合并后的内容直接输出:
import java.io.*;
public class MergeTXTFiles {
public static void main(String[] args) {
// 要读取的日期范围
String startDate = "2021-10-01";
String endDate = "2021-10-07";
// 合并后的文件输出路径
String outputPath = "/path/to/output.txt";
try {
// 创建输出流
PrintWriter writer = new PrintWriter(outputPath);
// 遍历日期范围内的文件夹
String currentDate = startDate;
while (currentDate.compareTo(endDate) <= 0) {
// 当前日期的文件夹路径
String folderPath = "/path/to/folders/" + currentDate;
// 检查文件夹是否存在
File folder = new File(folderPath);
if (folder.isDirectory()) {
// 遍历文件夹内的所有 TXT 文件
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile() && file.getName().endsWith(".txt")) {
// 读取文件内容并写入输出流
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
writer.println(line);
}
reader.close();
}
}
}
}
// 增加一天,进入下一个日期
currentDate = getNextDate(currentDate);
}
// 关闭输出流
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 获取下一个日期
private static String getNextDate(String currentDate) {
// 省略日期计算逻辑,根据当前日期计算并返回下一个日期
return currentDate;
}
}
在上述示例中,您需要修改以下部分以适应您的实际情况:
-
startDate
:要读取的日期范围的起始日期。 -
endDate
:要读取的日期范围的结束日期。 -
outputPath
:合并后的文件输出路径。
示例代码使用了一个循环来遍历指定日期范围内的文件夹。对于每个文件夹,它遍历文件夹下的所有 TXT 文件,将它们的内容逐行读取,并写入到一个输出流中。最后,将输出流中的内容写入到输出文件中。
请根据实际情况修改代码中的文件夹路径和输出路径,以确保文件夹存在并且能够访问到所需的 TXT 文件,并将合并后的内容正确地输出到指定的输出文件中。