Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Saving a file using a dialog box

  1. #1
    Junior Member
    Join Date
    Nov 2010
    Thanked 0 Times in 0 Posts

    Default Saving a file using a dialog box

    Why doesn't this very simple code work when it seems to me that it should?

    import java.io.*;
    import javax.swing.*;
    public class FileInput
        public static void main(String[] args)
        	String fileName =
    			JOptionPane.showInputDialog("Open file: ");
        	PrintWriter inputStream = null;
               inputStream = new PrintWriter(new File(fileName));
           catch(FileNotFoundException e)
               System.out.println("Error opening the file " + 
    All I expect it to do is to display the contents of a text file in the console of Eclipse...


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Thanked 619 Times in 561 Posts
    Blog Entries

    Default Re: Saving a file using a dialog box

    What do you mean by "doesn't work"?

    From the PrintWriter API, there's no constructor which will create a PrintWriter from just a file, you must have an OutputStream.

    inputStream = new PrintWriter(new FileOutputStream(new File(fileName)));

    Also, you're not printing anything out to the PrintWriter, so the file will be empty.

Similar Threads

  1. saving xml file
    By LOL in forum What's Wrong With My Code?
    Replies: 1
    Last Post: May 18th, 2010, 05:45 AM
  2. Replies: 0
    Last Post: April 10th, 2010, 05:52 PM
  3. Saving an image file (PGM format)
    By Mickey2315 in forum Algorithms & Recursion
    Replies: 3
    Last Post: September 12th, 2009, 01:18 AM
  4. [SOLVED] Saving A File?
    By MysticDeath in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: August 1st, 2009, 11:56 AM
  5. How to save statistics of a game in a binary file instead of txt file?
    By FretDancer69 in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: June 19th, 2009, 05:05 AM