tags:

views:

447

answers:

2

i have written a java program that opens all kind of files with a jfileChooser then i want to save it in another directory with JFileChooser save dialog, but it only saves a empty file. what can i do for saving part? thanks

+2  A: 

JFileChooser just returns the File object, you'll have to open a FileWriter and actually write the contents to it.

E.g.

if (returnVal == JFileChooser.APPROVE_OPTION) {
   File file = fc.getSelectedFile();
   FileWriter fw = new FileWriter(file);
   fw.write(contents);
   // etc...
} 

Edit:

Assuming that you simply have a source file and destination file and want to copy the contents between the two, I'd recommend using something like FileUtils from Apache's Commons IO to do the heavy lifting.

E.g.

FileUtils.copy(source, dest);

Done!

Kris
can you show me in a code snippet please?
samuel
thanks alot but what is contents?
samuel
contents is whatever you want to write to the file
Kris
but I thought the computer would do everything for me :(
willcodejavaforfood
A: 

Just in addition to Kris' answer - I guess, you didn't read the contents of the file yet. Basically you have to do the following to copy a file with java and using JFileChooser:

  1. Select the source file with the FileChooser. This returns a File object, more or less a wrapper class for the file's filename
  2. Use a FileReader with the File to get the contents. Store it in a String or a byte array or something else
  3. Select the target file with the FileChooser. This again returns a File object
  4. Use a FileWriter with the target File to store the String or byte array from above to that file.

The File Open Dialog does not read the contents of the file into memory - it just returns an object, that represents the file.

Andreas_D