Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

saving a text file using JFileChooser

 
Maysam Sorkhabi
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am very new to GUI and I've been experimenting with JFileChooser lately. I can choose a text file using JFileChooser and display it in a JTextArea. The problem is I don't know how to the opposite. Probably by obtaining some text from a JTextArea, storing it as a String and then using JFileChooser to navigate through system files, type in a file name, and have the chooser "Create" a file with the name that I specify and then writing the String to it.
Here is what I've don so far. I'm a noob to all of this and you help will be greatly appreciated.

final JFileChooser fc = new JFileChooser() ;
int returnVal = fc.showSaveDialog(jDesktopPane1) ;
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File current_file = fc.getCurrentDirectory() ;
try{current_file.createNewFile() ;}
catch(Exception e) {System.out.println("Somethin' went wrong") ;}

this does not seem to work!!
 
Joe Ess
Bartender
Posts: 9302
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Tutorial is always a good place to go for examples. This chapter is a good introduction on how to work with files.
The code that you have written:

actually attempts to create a new file with the same name as an existing directory, so we would not expect that to work. What you want to do is invoke getSelectedFile() on the file chooser dialog and create a FileOutputStream (see tutorial above) using that File.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic