简体   繁体   中英

Using PrintWriter to print a string to a text file, but when I open the text file it is empty

I'm using PrintWriter in Java to try to write some Strings to a text file, however when I open the text file it is empty.

Here is my code:

public void save(String fileName) throws FileNotFoundException{

    PrintWriter out1 = new PrintWriter("aSB.txt");
    out1.println("The Pupil's information is listed below:");
    for (Pupil pup : Pupils) {
       out1.println(pup.getFirstName() + " " + pup.getLastName());
    }
    out1.println("End");
    out1.println("The Club's information is listed below:");
    for (Club clu : Clubs) {
       out1.println(clu.getName());
    }
    out1.close();   
}

Why is the filename empty?

Try to catch FileNotFoundException and see if you have error creating the file. Also try catching SecurityException. If not try using FileOutputStream. It is really easy to use it Good luck!

As Kevin said, maybe directory issues. Try to specify the full path see what happens.

Something like:

PrintWriter pw = new PrintWriter("c:/asb.txt");

Alternatively, see here

quite possibly the array are empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM