以相反的顺序读取和写入文件 - Java

Liz*_*Liz 2 java io

我有一个非常大的文件(甚至可能是1G),我想以相反的顺序(在Java中)创建一个新文件.例如:

Original file:

This is the first line
This is the 2nd line
This is the 3rd line

The reversed file:

This is the 3rd line
This is the 2nd line
This is the first line
Run Code Online (Sandbox Code Playgroud)

由于文件非常大,一次将整个文件加载到内存并反转顺序可能会有问题(我可以使用的内存有限).我怎样才能在Java中实现这一目标?

谢谢

leo*_*loy 6

我很害怕,没什么特别直接的.但是你可以很容易地创建一些包含RandomAccessFile的 ReverseBufferedRead类.

另见这里.


Dan*_*Dan 5

通过几百行的块读取文件,颠倒块中行的顺序并将它们写入临时文件.然后以相反的顺序加入临时文件并清理.

换句话说,使用磁盘而不是内存.