save file with JFileChooser save dialog

后端 未结 3 636
我在风中等你
我在风中等你 2021-01-03 12:06

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 the JFileChooser save dialog, but it only sa

相关标签:
3条回答
  • 2021-01-03 12:36

    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.

    0 讨论(0)
  • 2021-01-03 12:38

    Something like..

    File file = fc.getSelectedFile();
    String textToSave = mainTextPane.getText();
    BufferedWriter writer = null;
    
    try
    {
    writer = new BufferedWriter( new FileWriter(file));
    writer.write(textToSave);
    JOptionPane.showMessageDialog(this, "Message saved. (" + file.getName()+")",
    "ImPhil HTML Editer - Page Saved",
    JOptionPane.INFORMATION_MESSAGE);
    }
    catch  (IOException e)
    { }
    
    0 讨论(0)
  • 2021-01-03 12:45

    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!

    0 讨论(0)
提交回复
热议问题