My question is, I guess, pretty simple :
Given one data.txt file, how to add some String in a line, line by line in java? I don’t want to delete the content, but simply add some string at the end of the line. Could you please show me a simple code for doing it?
Ex, given data.txt file:
aaa bbb ccc
eee fff ggg
Result after running the java program:
aaa bbb ccc ddd
eee fff ggg hhh
Additional question : is there a simple way to “insert” in the line line of a given file some String? If yes, how to do it too?
Result:
aaa 111 bbb ccc
eee fff 222 ggg
Thank you in advance for your help.
I don’t know of a simple way to do this, but there is a rather complicated way to do it, by reading the text from the file, editing it, then overwriting the file with the edited text.
First you need to read the file line by line into an array:
The code above basically sets an array to contain as many Strings as there are lines in the file, by calling the method below (which returns the number of lines of text in a file)…:
…then sets the array to contain the text in the file by calling this method for each line:
Having read the text file, you now need to do something to the Strings by using the
.concat()method which joins two Strings together. This code will do the example in the question:After this it calls the
writeFile()method which will write the array to the file. If you want to make the code more flexible you may wish to add another constructor to write a different array to the file:To answer your second question, it is possible to insert a word or words into a line, by using
StringTokenizerto split the string into words, then inserting a new word into the line of text. StringTokenizer splits the string into words and calling $Tokenizer1.nextToken() returns the next word in the String. Here is an example for this that has the result specified in your question:However to make this work with the rest of the code you will have to edit these sections:
Using the
doSomethingToStrings()method changes the file from this:to this:
Using the
doSomethingElseToStrings()method changes the file to this:I hope this is useful to you!