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:
package addtext;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Dan300
*/
public class AddText {
File yourFile = new File("YourFileHere.txt"); //add the name of your file in the brackets
int numLines; //this will store the number of lines in the file
String[] lines; //the lines of text that make up the file will be stored here
public AddText() {
numLines = getNumberLines(yourFile);
lines = new String[numLines];//here we set the size of the array to be the same as the number of lines in the file
for(int count = 0; count < numLines; count++) {
lines[count] = readLine(count,yourFile);//here we set each string in the array to be each new line of the file
}
doSomethingToStrings();
}
public static void main(String[] args) {
new AddText();
}
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)...:
public int getNumberLines(File aFile) {
int numLines = 0;
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){ //ReadLine returns the contents of the next line, and returns null at the end of the file.
numLines++;
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return numLines;
}
...then sets the array to contain the text in the file by calling this method for each line:
public String readLine(int lineNumber, File aFile) {
String lineText = "";
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
for(int count = 0; count < lineNumber; count++) {
input.readLine(); //ReadLine returns the contents of the next line, and returns null at the end of the file.
}
lineText = input.readLine();
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return lineText;
}
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:
public void doSomethingToStrings() {
try {
lines[0] = lines[0].concat(" ddd"); //this joins the two strings lines[0] and " ddd"
} catch (ArrayIndexOutOfBoundsException ex) { // I have added a try{}catch{} block so that if there is not as many lines in the file as expected, the code will still continue.
}
try {
lines[1] = lines[1].concat(" hhh");
} catch (ArrayIndexOutOfBoundsException ex) {
}
try {
writeFile(yourFile);
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
Logger.getLogger(AddText.class.getName()).log(Level.SEVERE, null, ex);
}
}
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:
public void writeFile(File aFile) throws FileNotFoundException, IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
BufferedWriter output = new BufferedWriter(new FileWriter(aFile));
try {
for(int count = 0; count < numLines; count++) {
output.write(lines[count]);
if(count != numLines-1) {// This makes sure that an extra new line is not inserted at the end of the file
output.newLine();
}
}
}
finally {
output.close();
}
}
To answer your second question, it is possible to insert a word or words into a line, by using StringTokenizer
to 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:
public void doSomethingElseToStrings() {
try{
StringTokenizer splitString1 = new StringTokenizer(lines[0]);
newLines[0] = splitString1.nextToken();
for(int count=0;count<=splitString1.countTokens();count++) {
if(count == 0) {
newLines[0] = newLines[0].concat(" 111");
}
newLines[0] = newLines[0].concat(" ");
newLines[0] = newLines[0].concat(splitString1.nextToken());
}
} catch(ArrayIndexOutOfBoundsException ex) {
}
try {
StringTokenizer splitString2 = new StringTokenizer(lines[1]);
newLines[1] = splitString2.nextToken();
for(int count=0;count<=splitString2.countTokens();count++) {
if(count == 1) {
newLines[1] = newLines[1].concat(" 222");
}
newLines[1] = newLines[1].concat(" ");
newLines[1] = newLines[1].concat(splitString2.nextToken());
}
} catch(ArrayIndexOutOfBoundsException ex) {
}
try {
writeFile(yourFile);
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
Logger.getLogger(AddText.class.getName()).log(Level.SEVERE, null, ex);
}
}
However to make this work with the rest of the code you will have to edit these sections:
public class AddText {
String[] newLines; // <<add
File yourFile = new File("YourFileHere.txt"); //add the name of your file in the brackets
int numLines;
String[] lines;
public AddText() {
...
//doSomethingToStrings(); <<delete
doSomethingElseToStrings(); // <<add
}
public void writeFile(File aFile) throws FileNotFoundException, IOException {
...
//output.write(lines[count]); <<delete
output.write(newLines[count]); // <<add
...
}
Using the doSomethingToStrings()
method changes the file from this:
aaa bbb ccc
eee fff ggg
(other text)
to this:
aaa bbb ccc ddd
eee fff ggg hhh
(other text remains the same)
Using the doSomethingElseToStrings()
method changes the file to this:
aaa 111 bbb ccc
ddd eee 222 fff
(other text remains the same)
I hope this is useful to you!