Java读取单个文件并写出多个文件 [英] Java read in single file and write out multiple files

查看:338
本文介绍了Java读取单个文件并写出多个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个简单的Java程序以读取文本文件,然后每当检测到空白行时写出一个新文件.我已经看到了读取文件的示例,但是我不知道如何检测空白行并输出多个文本文件.

I want to write a simple java program to read in a text file and then write out a new file whenever a blank line is detected. I have seen examples for reading in files but I don't know how to detect the blank line and output multiple text files.

fileIn.txt:

line1
line2

line3

fileOut1.txt:

line1
line2

fileOut2.txt:

line3

推荐答案

仅在文件包含特殊字符的情况下,也许您应该指定编码.

Just in case your file has special characters, maybe you should specify the encoding.

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读取单个文件并写出多个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆