2

I have the above code. What i wanna do is to write in a txt file a string.

     import java.io.*;
    import java.util.*;

    public void writeAsfalizomenos(asfalizomenos myObj) throws IOException {

    Scanner scanner = new Scanner(System.in);
    System.out.print("Surname: ");
    String username = scanner.nextLine();
    System.out.println(username);


    FileWriter outFile = new FileWriter("asdf.txt", true);
    PrintWriter out1 = new PrintWriter(outFile);

    out1.append(username);
    out1.println();
    out1.append("adfdas");



    //
    // Read string input for username
    //



}

public static void main(String [] args) throws IOException{


    asfalizomenos a = new asfalizomenos();
    a.writeAsfalizomenos(a);
}

The above code creates a txt file but it doesnt write the string to it. Any idea about my bug??

snake plissken
  • 2,649
  • 10
  • 43
  • 64
  • If you plan to write a lot of text, the java api recommends wrapping your `PrintWriter` in a `BufferedWriter`. There is a code sample in the api itself. http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html As others have point out, you are not closing your `PrintWriter` – Ali Aug 10 '11 at 22:21

2 Answers2

6

You're not closing or flushing the PrinterWriter or the FileWriter. So basically it's being buffered, so nothing is being written to the file.

You should close both in finally blocks:

FileWriter outFile = new FileWriter("asdf.txt", true);
try {
    PrintWriter out1 = new PrintWriter(outFile);
    try {
        out1.append(username);
        out1.println();
        out1.append("adfdas");
    } finally {
       out1.close();
    }
} finally {
   outFile.close();
}

Closing will flush automatically.

(I can't remember - it's likely that closing the PrintWriter will close the FileWriter. Personally I like to be explicit about it anyway.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yeah man thanks. The printerwriter is the one that must close. – snake plissken Aug 11 '11 at 09:10
  • @snake: As I say, that should close the `FileWriter` too - but personally I would close both. I'd also use `FileOutputStream` wrapped in an `OutputStreamWriter`, specifying the encoding, but that's a separate matter. – Jon Skeet Aug 11 '11 at 09:15
1

Close the PrintWriter after you're done writing to it:

out1.close();
tskuzzy
  • 35,812
  • 14
  • 73
  • 140