Is it possible to change ONE line in a txt file WITHOUT reading and writing the whole file (Java)?

筅森魡賤 提交于 2020-01-30 04:45:32

问题


Say I have a text file:

I love bananas.
<age> 23 </age> years old.
I like beaches.

All I want to do is open said file and change the age to 24 or 25. Any way to do that in Java WITHOUT reading a writing the whole file? I know its possible with buffered reader and writer, but I am looking for a less memory intensive way when the file gets to be huge.


回答1:


Short answer: no.

Long answer: Not really. If you know that the text you're inserting directly replaces the text you're removing you could perform a substitution by seeking to the portion of the file, reading a small block, substituting the new text and replacing that block. This would work for your age replacement example, but not if you're replacing 9 with 10, or 99 with 100, for example.

However, there are other difficulties:

You may have variable length lines, so you don't know where to seek to. You will still have to read the file as far as the place you make the substitution, even if you do it a block at a time and discard the unwanted ones.

You have a further complexity with multi-byte character sets like UTF-8. Your ingoing text may display as the same length as your outgoing text, but may be shorter or longer depending on the substitution.

e (U+0065) codes as one byte, but é (U+00E9) codes as two.

But, if you're just looking for a less memory intensive method you can read a file one line at a time, and write each line to a new file as you process it. When you're done, delete the old file and rename the new one. This might be slow, so buffering reads and writes to, say, 20 lines (or 100, or 1000, or whatever you choose..) will improve performance.




回答2:


I found that Hobo was correct with you can replace "23" with "99" but not 100. I was able to use this:

Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(file_paths), charset);
content = content.replaceAll(OldNumber,Integer.toString(NewNumber)); 
Files.write(file_paths, content.getBytes(charset)); // Writes it back to the file.

In addition there are two others methods: Filename.utils in Apache AND Random File Access Method. To find what you want to replace use .replace command!



来源:https://stackoverflow.com/questions/30631668/is-it-possible-to-change-one-line-in-a-txt-file-without-reading-and-writing-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!