在Java中的文本文件中切换两行 [英] Switching two lines in a text file in Java

查看:109
本文介绍了在Java中的文本文件中切换两行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经坚持了一段时间,我终于决定请求帮助. 因此,我有一个小的文本文件,用户想要从中切换2行,用户输入2行的索引,因此我必须切换em. 到目前为止,我的想法是使用带有2个正则表达式的replaceALL ,但是A:可能不会切换它们,而只是最终将它们替换为另一个,给我留了一个副本,而B:我不知道如何使用正则表达式来定位第n行; 或使用-Files.readAllLines(Paths.get(name)).get(index);得到两条线,但是我仍然在实际切换过程中苦苦挣扎.

I've been stuck on this for a while and I've finally decided to plead for help. So I have a small text file and the user wants to switch 2 lines from it, the user enters the indexes of the 2 lines and I have to switch em. So far my ideas have been to either use replaceALL with 2 regexes , but A: That probably won't switch them but just end up replacing one with the other, leaving me with a duplicate and B: I have no idea how to locate the nth line using regex; or use - Files.readAllLines(Paths.get(name)).get(index); to get the two lines but then I'm still struggling with the actual switching process.

推荐答案

您可以使用

  • Files.readAllLines将所有行作为列表获取
  • 交换列表的两个元素.例如Collections.swap
  • 写回所有行以更新文件.
  • Files.readAllLines to get all lines as a list
  • swap the two elements of the list. e.g. Collections.swap
  • write all the lines back out to update the file.

如果您需要能够处理大文件,则可以

If you need to be able to work with large files you could

  • 使用RandomAccessFile通过从文件的开头进行读取来查找所需行的开头/结尾.
  • 将这两行读入缓冲区.
  • 将两行写到位,但四处交换.

这篇关于在Java中的文本文件中切换两行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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