gpt4 book ai didi

Java读入单个文件并写出多个文件

转载 作者:行者123 更新时间:2023-11-29 06:00:01 24 4
gpt4 key购买 nike

我想编写一个简单的 java 程序来读取文本文件,然后在检测到空白行时写出一个新文件。我看过读取文件的示例,但我不知道如何检测空行并输出多个文本文件。

文件输入.txt:

line1
line2

line3

fileOut1.txt:

line1
line2

fileOut2.txt:

line3

最佳答案

以防万一您的文件有特殊字符,也许您应该指定编码

FileInputStream inputStream = new FileInputStream(new File("fileIn.txt"));
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
int n = 0;
PrintWriter out = new PrintWriter("fileOut" + ++n + ".txt", "UTF-8");
for (String line;(line = reader.readLine()) != null;) {
if (line.trim().isEmpty()) {
out.flush();
out.close();
out = new PrintWriter("file" + ++n + ".txt", "UTF-8");
} else {
out.println(line);
}
}
out.flush();
out.close();
reader.close();
streamReader.close();
inputStream.close();

关于Java读入单个文件并写出多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10543053/

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