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

时间:2012-05-10 22:28:02

标签: java fileinputstream fileoutputstream

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

fileIn.txt:

line1
line2

line3

fileOut1.txt:

line1
line2

fileOut2.txt:

line3

5 个答案:

答案 0 :(得分:1)

您可以检测到空字符串,以查明某行是否为空。例如:

if(str!=null && str.trim().length()==0)

或者你可以做(​​如果使用JDK 1.6或更高版本)

if(str!=null && str.isEmpty())

答案 1 :(得分:1)

  

我不知道如何检测空行..

if (line.trim().length==0) { // perform 'new File' behavior
  

..并输出多个文本文件。

在循环中对单个文件执行的操作。

答案 2 :(得分:1)

如果您的文件包含特殊字符,也许您应该指定编码

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

答案 3 :(得分:0)

BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
 // Line is empty
 }
}

上面的代码段可用于检测该行是否为空,此时您可以创建FileWriter来写入新文件。

答案 4 :(得分:0)

这样的事情应该做:

public static void main(String[] args) throws Exception {
        writeToMultipleFiles("src/main/resources/fileIn.txt", "src/main/resources/fileOut.txt");
    }

    private static void writeToMultipleFiles(String fileIn, String fileOut) throws Exception {      

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileIn))));
        String line;
        int counter = 0;
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileOut))));

        while((line=br.readLine())!=null){

            if(line.trim().length()!=0){
                wr.write(line);
                wr.write("\n");
            }else{
                wr.close();
                wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut + counter)));
                wr.write(line);
                wr.write("\n");
            }
            counter++;
        }

        wr.close();
    }