简体   繁体   中英

How to read contents of a template file make changes and save as new file?

I have a file lets call it template.cfg and I want to make changes to it and save the file with a new name preserving the template file.

Template file contents. There is alot more in the file however these are the online lines i'm concerned about.

<property>URL</property>
<property>PASSWORD</property>
<property>SCHEMA</property>
<property>USER</property>

Output file I want to have a new name lets call it databaseInfo.cfg So i'd need to search for the words URL and replace it with a user defined URL same with PASSWORD SCHEMA and USER. I would also like to save it in the same directory as the template.

<property>foo</property>
<property>bar</property>
<property>D2D</property>
<property>D2Duser</property>

I'm thinking in terms like Save As. not sure how I should go about modifying the file without changing the original and yet saving it as a new file.

I dont have any code yet outside of getting the template files full path to open the file because I'm curious what is the best route to take from having the file.

File file = new File(template.cfg);
String fullPath = file.getAbsolutePath();

You can simultaneously run a Scanner to read the text from the old file, modify the text using String manipulation operations, and use a PrintWriter to write the output strings to a new file. That way, you would have both the old file and the new file.

Alternatively, if your text replacements are particularly straightforward, you could do away with Java altogether and manipulate it on the UNIX command line with the "sed" command. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM