每两行java替换一行到上面的行

时间:2016-06-17 20:11:22

标签: java file

我有一个这样的文本文件:

Emma,F,20355
Olivia,F,19553
Sophia,F,17327
Ava,F,16286
Isabella,F,15504
Mia,F,14820
Abigail,F,12311
Emily,F,11727

我想在,之后删除单词,并且每两行在一行中放两行。 例如:

Emma Olivia
Sophia Ava
Isabella Mia
Abigail Emily

程序可以完成第一部分,但我不知道程序如何处理第二部分。我可以在第一个,之后拆分单词和数字,但我遇到了如何排列行。

以下是代码:

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String[] a;
String res;
while ((currentLine = reader.readLine()) != null) {
    a = currentLine.split(",");
    res = a[0] + "\n";
    writer.write(res);
}
writer.close();
reader.close();

我想我需要在while循环中创建一个for循环,但是我不知道写什么来计算偶数或奇数行。

5 个答案:

答案 0 :(得分:2)

更改为以下内容:

int count = 1;
while ((currentLine = reader.readLine()) != null) {
    a = currentLine.split(",");
    res = a[0] + count % 2 == 0 ? "\n" : " ";
    count++;
    writer.write(res);
}

答案 1 :(得分:2)

try (
    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))
) {
    while (true) {
        String line1 = reader.readLine();
        if (line1 == null) { 
            break;
        }
        writer.write(line1.split(",", 2)[0]);

        String line2 = reader.readLine();
        if (line2 == null) {
            writer.newLine();
            break;
        }
        writer.write(" " + line2.split(",", 2)[0]);
        writer.newLine();
    }
}

答案 2 :(得分:1)

int newLine = 1;
while ((currentLine = reader.readLine()) != null) {
    a = currentLine.split(",");
    if (newLine % 2 == 0)
        res += a[0] + "\n";
    else
        res += a[0] + " ";
    newLine++;
}
writer.write(res);

答案 3 :(得分:1)

如果读卡器中还有第二行,请尝试同时读取两行。

这样的事情:

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String[] a;
String[] b;
String res;
while ((currentLine = reader.readLine()) != null) {
    a = currentLine.split(",");
    if (reader.hasNext()) {
        b = reader.readLine().split(",");
        res = a[0] + " " + b[0] + "\n";
    } else {
        res = a[0]+"\n";
    }
    writer.write(res);
}
writer.close();
reader.close();

答案 4 :(得分:0)

如上所述,一次读两行。将它们组合起来,然后根据分隔符(逗号)进行拆分 - 然后应该很容易将新格式写入文本文件(也许可以将结果弹出一个列表,然后遍历列表将其写出来。

这不是一个完整的解决方案,但应该足以让你明白这一点。

// Read two lines at a time
String currentLine = reader.readLine(); //Emma,F,20355
String nextLine = reader.readLine();    //Olivia,F,19553

String combinedLine = currentLine + "," + nextLine;

// split into separate elements
String[] elements = combinedLine.split(",");

List<String> newLines = new ArrayList<>();
newLines.add(elements[0] + " " + elements[3]);

for (final String line : newLines) {
    // write to file
    writer.write(res);
}