1

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

文件输入.txt:

line1
line2

line3

文件输出1.txt:

line1
line2

文件输出2.txt:

line3
4

5 回答 5

1

您可以检测一个空字符串来确定一行是否为空。例如:

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

或者您可以这样做(如果使用 JDK 1.6 或更高版本)

if(str!=null && str.isEmpty())
于 2012-05-10T22:33:21.280 回答
1

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

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

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

循环执行对单个文件所做的操作。

于 2012-05-10T22:34:54.077 回答
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();
于 2012-05-10T23:15:21.390 回答
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以写入新文件。

于 2012-05-10T22:37:36.990 回答
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();
    }
于 2012-05-10T22:52:35.263 回答