Supposed I have a file called myfile.txt, its content is below:
I would like to open it, go to the "keyword", modify the string "mykeyword" to "changedkeyword" then save the file. Note that I want to save the change to the file, not to create another file. What should I do?
Now I know many of you will suggest me reading I/O classes. I know I/O classes but still couldn't find what I want. A simple source code would be great.
sed -i s/mykeyword/changedkeyword/ filename
1) Read the entire file into memory, close the file stream. Modify the in-memory string. Open the file and write it back.
2) For each line in the file, read it and replace any words, writing each line to a new file. Close both files. Delete the first, rename the second to the first.
I know both these solutions. However, I'm looking for an efficient one as I need to do this many times in my program. And I think these solutions could be optimized much. Both your solution need to erase the whole file while all I need is modify one keyword. Immagine you have a big file but you only need to modify a words of 6 to 7 characters.
Okay then. If the word is the exact same size, then simply locate it and write the new word. Thats one optimization.
Another is to read until you find the word. Then read a buffer of size n+(replacement.length-original.length). Write the replaced word, then the buffer and continue until done.
How big are your files and how many of them and how timely do you have to be in this operation?
The file size could reach MB, fortunately I only need to replace 1 keyword and it locates at very near beginning. The keyword size could be considered fixe.
Could you give me a sample code to show how to replace the old word by the new word? I could easily open the file in any mode and locate the pointer to the keyword.
The most flexible access is probably to memory map the file, you need to get the Channel and map it to a ByteBuffer.
You'll need to manipulate to file as bytes. Convert the text with String.getBytes and overwrite the relevant part of the buffer.