I know we are supposed to add a snipit of code to our questions, but I am seriously dumbfounded and can't wrap my head or find any examples to follow from.
Basically I want to open file C:\A.txt , which already has contents in it, and write a string at the end. Basically like this.
File A.txt contains:
John
Bob
Larry
I want to open it and write Sue at the end so the file now contains:
John
Bob
Larry
Sue
Sorry for no code example, my brain is dead this morning....
Please Search Google given to the world by Larry Page and Sergey Brin.
BufferedWriter out = null;
try {
FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
out = new BufferedWriter(fstream);
out.write("\nsue");
}
catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
finally {
if(out != null) {
out.close();
}
}
To expand upon Mr. Eels comment, you can do it like this:
File file = new File("C:\\A.txt");
FileWriter writer;
try {
writer = new FileWriter(file, true);
PrintWriter printer = new PrintWriter(writer);
printer.append("Sue");
printer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't say we ain't good to ya!
Suggestions:
true
would allow appending text into the File if it exists. println(...)
on your PrintWriter, writing your new text into the file.close()
of the PrintWriter should be in the try's finally block.e.g.,
PrintWriter pw = null;
try {
File file = new File("fubars.txt");
FileWriter fw = new FileWriter(file, true);
pw = new PrintWriter(fw);
pw.println("Fubars rule!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
}
}
Easy, no?
Source: Stackoverflow.com