20

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

RedHatcc
  • 3,016
  • 4
  • 16
  • 13
  • 14
    Oh this post is on geek-and-poke! http://geek-and-poke.com/geekandpoke/2013/11/10/indirection – Lai Nov 11 '13 at 04:07

3 Answers3

45

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();
    }
}
Belphegor
  • 4,456
  • 11
  • 34
  • 59
Addicted
  • 1,694
  • 1
  • 16
  • 24
13

Suggestions:

  • Create a File object that refers to the already existing file on disk.
  • Use a FileWriter object, and use the constructor that takes the File object and a boolean, the latter if true would allow appending text into the File if it exists.
  • Then initialize a PrintWriter passing in the FileWriter into its constructor.
  • Then call println(...) on your PrintWriter, writing your new text into the file.
  • As always, close your resources (the PrintWriter) when you are done with it.
  • As always, don't ignore exceptions but rather catch and handle them.
  • The 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?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
4

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!

Malcolm Smith
  • 3,540
  • 25
  • 29
  • 3
    1+ to ya, but don't forget to close the print writer in the finally block, not in the try block. You don't want any dangling resources. See my example to see what I mean. – Hovercraft Full Of Eels May 19 '12 at 18:29