是否有可能改变一个txt文件中的一行而不读写整个文件(Java)? [英] Is it possible to change ONE line in a txt file WITHOUT reading and writing the whole file (Java)?

查看:112
本文介绍了是否有可能改变一个txt文件中的一行而不读写整个文件(Java)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个文本文件:

 我喜欢香蕉。 
<年龄> 23< / age>岁。
我喜欢海滩。

我想要做的只是打开上述文件并将其年龄更改为24或25。在Java中这样做没有读一个文件的整个文件?我知道它可能使用缓冲读写器,但是当文件变得庞大的时候,我正在寻找一种占用更少内存的方式。

解决方案

我发现Hobo是正确的,你可以用99替换23而不是100.我可以使用这个:

  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)); //将其写回文件。另外还有其他两种方法: Apache中的Filename.utils 和中的 Filename.utils 随机文件访问方法。要找到你想要替换使用.replace命令!

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.

解决方案

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!

这篇关于是否有可能改变一个txt文件中的一行而不读写整个文件(Java)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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