是否有很好的方法来用Java交换文本文件中的每两行顺序?

问题描述 投票:-6回答:3

如果我的文本文件看起来像:

8 3
7 5 4
2
5 6 8 10

我希望它看起来像

7 5 4
8 3
5 6 8 10
2

每行中的数字量可以相同或不同。

java
3个回答
0
投票

尝试这种方法(我假设您的源文件具有偶数行):

  1. 开源文件(source_file
  2. 创建临时文件(temp_file
  3. source_fileline1)读取行
  4. source_fileline2)读取下一行
  5. line2写到temp_file
  6. line1写入temp_file
  7. 重复直到source_file结束
  8. 关闭source_file
  9. 关闭temp_file
  10. 删除source_file
  11. temp_file重命名为source_file

您可能会问,为什么我要制作一个新文件。对于小文件,您可以读取数组的所有行并替换该数组的每两个项目,然后将结果放入同一文件。

但是对于大文件,这种方法是不可接受的。因此,我建议采用更通用的方法。


0
投票

您可以通过简单的循环功能来完成。

首先使用fileReader从文件中读取行并由BufferReader对其进行包装。

然后使用字符串数组存储BufferReader中的所有行。

之后,执行下面的代码

public void testing() {
        String[] arr = new String[4];
        arr[0] = "8 3";
        arr[1] = "7 5 4";
        arr[2] = "2";
        arr[3] = "5 6 8 10";
        String current, previous;
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            current = arr[i];
            if (count == 1) {
             //1st way
                previous = arr[i - 1];
                arr[i - 1] = current;
                arr[i] = previous;
            //End of 1st way
            //2nd way
              //arr[i] = arr[i - 1];
              //arr[i - 1] = current;
           //End of 2nd way
            }
            if (count == 1) {
                count = -1;
            }
            count++;
        }
    }

最后,将字符串数组写入文件。

如Rafael所述,此数组交换方法适用于小文件,但不适用于大文件。我认为您的文件很小。


0
投票

拉斐尔有正确的做法。在循环中,您将从文件中读取文件,并同时写入新文件。您可以使用模数运算符来检测何时处于奇数行或偶数行。

在奇数行上,将该行存储在temp变量中。在偶数行上,按照需要的顺序将当前行和temp变量中存储的行写到新文件中。]

完成后重命名新文件。

每次编写两行代码时,请将temp变量设置为空,然后可以在循环后进行测试。如果文件中的行数为奇数,则该温度将保留尚未写入的行,因此将其写为最后一行。这是为了分配任务上的奖励点……文件的行数很奇怪。

使用数组确实不好...如果文件很大,该怎么办?真的很大吗?

此外,此作业通常用于向学生介绍孤独的模运算符。

    if (i % 2 == 0)
      System.out.println("The number is even.");
    else
      System.out.println("The number is odd.");

模数(%)是您如何知道所在行的...奇数或偶数。 (从1开始,而不是从0开始循环。)

祝你好运。>>

© www.soinside.com 2019 - 2024. All rights reserved.