File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Writing data to a text file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Writing data to a text file" Watch "Writing data to a text file" New topic

Writing data to a text file

mary caldwell

Joined: Oct 16, 2008
Posts: 9
Hello everyone,
I'm having trouble writing data to a text file. The code I have right now compiles and even gives me System.out.println messages that suggest it is working, but it doesn't seem to be actually creating the text file (or at least I can't find it). Any help with this would be awesome. Thanks in advance!

Paul Clapham

Joined: Oct 14, 2005
Posts: 18993

What's with putting quotes in the filename? In Windows I'm not allowed to create files with quotes in their names. You're probably using Windows too, and even if you aren't, that probably isn't a valid filename.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 40064
Probably best to print rather more details from the catch; a stack trace might give useful information.
mary caldwell

Joined: Oct 16, 2008
Posts: 9
I'm actually on a mac, but I was just trying the quotes out to see if it made a difference (it didn't). My catch block is not catching anything, either (when I run, it prints the "working" from within the try block).
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14435

First, change the content of the catch block as follows:

This way, you will get more useful information than just "not working" if an IOException is thrown.

Second, after the file.close(); statement, put a System.out.println statement to print "done", and see if it gets printed - there might be a runtime exception happening that you don't see.

Also, don't do this: new File("\"" + filename + "\"")

It will create a file with literally quotes in the name. That's most likely not what you want. Just do this: new File(filename)

Finally, call file.flush() before file.close() to make sure that BufferedWriter writes its cache to the file.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
mary caldwell

Joined: Oct 16, 2008
Posts: 9
Thank you everyone for the replies. It apparently is creating the text file correctly now (it works when I call my load file method), but I still can't find where it is saving to.... hmm... oh well! At least it works, if mysteriously. Thanks again!
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
Change the first line of the try block to
This will print out the filename you supply and the absolute path of your file that Java uses. These may or may not be the same. If they are different and you don't understand why, come back and someone should be able to explain.

I agree. Here's the link:
subject: Writing data to a text file