用Java替换文本文件的第一行

用Java替换文本文件的第一行

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

问题描述

我有一个文本文件,我只想更改文件的第一行。该文件可能是数百万行,所以我宁愿不必遍历所有内容,所以我想知道是否还有其他方法可以做到这一点。

I have a text file where I want to change only the first line of the file. The file could be millions of rows long, so I'd rather not have to loop over everything, so I'm wondering if there is another way to do this.

我还想在第一行应用一些规则,以便用其他单词替换某些单词的实例。

I'd also like to apply some rules to the first line so that I replace instances of certain words with other words.

这可能吗?

推荐答案

A 将执行此操作,除非结果行的长度与原始行的长度不同。

A RandomAccessFile will do the trick, unless the length of the resulting line is different from the length of the original line.

如果事实证明你被迫执行副本(第一行被替换,其余数据按原样复制),我建议使用 。首先使用 BufferedReader readLine()来读取第一行。修改它并将其写入 BufferedWriter 。然后使用 char [] 数组执行文件其余部分的暴力拷贝。这比逐行复制更有效。如果您需要详细信息,请告诉我。

If it turns out you are forced to perform a copy (where the first line is replaced and the rest of the data shall be copied as-is), I suggest using a BufferedReader and BufferedWriter. First use BufferedReader's readLine() to read the first line. Modify it and write it to the BufferedWriter. Then use a char[] array to perform a brute-force copy of the remainder of the file. This will be more efficient than doing the copy line by line. Let me know if you need details..

另一种选择是在同一文件中执行读写操作。但它会有点复杂。 :)如果您需要有关详细信息,请告诉我..

Another option is to perform the reading and writing inside the same file. It'll be a bit more complex though. :) Let me know if you need details on this as well..

这篇关于用Java替换文本文件的第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:52