在java中,如何编辑文本文件的1行?
好的,我知道该行的值,但我没有行号,我如何只编辑 1 行?
它是一个配置文件,即 x=y 我想要一个命令将 x=y 编辑为 x=y,z。
甚至 x=z。
Ok so I know the value of the line, I dont have the line number, how would I edit only 1 line?
Its a config file, i.e
x=y
I want a command to edit x=y to x=y,z.
or even x=z.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 Java 中,您可以使用 `Properties 类:
app.config 文件:
java:
In Java you can use `Properties class:
app.config file:
java:
如果您正在使用该配置格式,您可能需要使用
用于读取/写入该文件的
组件。但如果您只想手动编辑它,则可以 逐行读取文件并匹配要更改的变量。
If you are using that configuration format, you might want to use
component to read/write on that file.
But if you just want to edit it by hand, you can just read the file line by line and match the variable you want to change.
一种方法是:
这有很多变体。当您写入文件的新版本时,您还需要小心,以防止在写入过程中出现问题时丢失所有内容。 (通常,您将新版本写入临时文件,重命名旧版本(例如作为备份),然后重命名新版本来代替旧版本。)
不幸的是,无法添加或删除字符位于常规文本文件的中间,而无需重写文件的大部分内容。这个“问题”并不是Java特有的。它是大多数主流操作系统上文本文件建模/表示方式的基础。
One way to do it is to:
There are many variations on this. You also need to take care when you write the new version of the file to guard against losing everything if something goes wrong during the write. (Typically you write the new version to a temporary file, rename the old version out of the way (e.g. as a backup) and rename the new version in place of the old one.)
Unfortunately, there is no way to add or remove characters in the middle of a regular text file without rewriting a large part of the file. This "problem" is not specific to Java. It is fundamental to the way that text files are modelled / represented on most mainstream operating systems.
除非新行的长度与旧行的长度完全相同,否则最好的选择是
如果你的配置文件很小,你也可以进行整个解析/修改步骤在内存中,然后将最终结果写回配置文件,这样您就可以跳过临时文件(尽管临时文件是防止在写入文件时出现问题时损坏的好方法)。
如果这不是您想要的,您应该编辑您的问题以使其更加清晰。我只是猜测你在要求什么。
Unless the new line has the exact same length as the old one, your best bet is to
IF your config file is small, you can also do the whole parsing/modification step in memory and then write the final result back to the config file, that way you skip the temporary file (although a temporary file is a good way to prevent corruption if something breaks while you write the file).
If this is not what you're looking for, you should edit your question to be a lot more clear. I'm just guessing what you're asking for.
如果您的数据都是键和值对,例如...
key1=value1
key2=value2
...,则将它们加载到 Properties 对象中。在我的脑海中,您需要一个 FileInputStream 来加载属性,使用 myProperties.put(key, value) 进行修改,然后使用 FileOutputStream 保存属性。
希望这有帮助!
右旋
If your data is all key and value pairs, for example ...
key1=value1
key2=value2
... then load them into a Properties object. Off the top of my head, you'll need a FileInputStream to load the properties, modify with myProperties.put(key, value) and then save the properties with the use of a FileOutputStream.
Hope this helps!
rh