Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java File - Open A File And Write To It [closed]

Tags:

java

file

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....

like image 372
RedHatcc Avatar asked May 19 '12 18:05

RedHatcc


People also ask

How do you close a file if it is open in Java?

If a File is opened you won't be able to close it via Java because, in order to close it, you would have to have it opened in your Java code. What you can do is to create a list and add all Files that have failed and then at the end of your processing try to process those Files again.

Can you read and write to the same file in Java?

You can't open the same file to read and write at the same time. You have to open and save the file information in a data structure and then close it. Then you have to work with the data structure in memory and open the file to write results. And when you finish to write you should close it.


1 Answers

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();
    }
}
like image 76
Addicted Avatar answered Sep 21 '22 12:09

Addicted