In java, how do I edit 1 line of a text file?

Ok, so I know the value of the line, I do not have a line number, how would I edit only one line?

Its configuration file, i.e. x = y I need a command to edit x = y for x = y, z.

or even x = z.

+4
source share
5 answers

In Java, you can use the Properties class:
App.config file:

x=y 

Java:

  public void writeConfig() throws Exception { Properties tempProp = new Properties(); tempProp.load(new FileInputStream("app.config")); tempProp.setProperty("x", "y,z"); tempProp.store(new FileOutputStream("app.config"), null); } 
+2
source

If you use this configuration format, you can use

java.util.Properties

to read / write in this file.

But if you just want to edit it manually, you can just read the file line by line and map the variable you want to change.

+2
source

One way to do this:

  • Read the file in memory; for example, as an array of strings representing the lines of a file.
  • Find the line / line you want to change.
  • Use regex (or other) to change line / line
  • Write the new version of the file from the version in memory.

There are many variations to this. You also need to take care when you write a new version of the file to protect against the loss of everything if something goes wrong during recording. (Usually, you write the new version to a temporary file, rename the old version in the path (for example, as a backup) and rename the new version instead of the old one.)

Unfortunately, there is no way to add or remove characters in the middle of a regular text file without overwriting a large part of the file. This "problem" is not specific to Java. It is crucial that text files are modeled / presented on most major operating systems.

+1
source

If the new line is the same length as the old one, best

  • Open temporary output file
  • Read the configuration file line by line
  • Key Search
  • If you cannot find it, just write the line you just read into the output file
  • If you can find it, write the new value in a temporary file instead
  • Until you hit EOF
  • Delete old file
  • Rename the new file to the old file

If your configuration file is small, you can also perform the entire parsing / changing step in memory, and then write the final result back to the configuration file, thereby skipping the temporary file (although the temporary file is a good way to prevent corruption if something breaks when you write a file).

If this is not what you are looking for, you should change your question to be much clearer. I just guess what you're asking for.

0
source

If your data is all key and value pairs, for example ...

key1 = value1

key2 = value2

... then load them into the Properties object. At the top of my head, you'll need a FileInputStream to load properties, change using myProperties.put (key, value), and then save the properties using FileOutputStream.

Hope this helps!

rel

0
source

Source: https://habr.com/ru/post/1332990/


All Articles