0

I have chosen file using

File file = fileChooser.getSelectedFile();

Now I want to write this file chosen by user to another location when user clicks save button. How to achieve that using swing?

kinkajou
  • 3,664
  • 25
  • 75
  • 128
  • 7
    Swing can't do anything for you since Swing handles only UI, not File manipulation. However, you can do it by either copying the bytes from the selected file to the target file yourself, or using FileUtils from apache commons-io: http://docs.oracle.com/javase/tutorial/essential/io/copy.html and http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html#copyFile(java.io.File,%20java.io.File) – Guillaume Polet Apr 27 '12 at 15:04

4 Answers4

2

To select the file you need something like ,

    JFileChooser open = new JFileChooser();
    open.showOpenDialog(this);
    selected = open.getSelectedFile().getAbsolutePath(); //selected is a String 

...and to save a copy ,

    JFileChooser save = new JFileChooser();  
    save.showSaveDialog(this);  
    save.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    tosave = fileChooser.getSelectedFile().getAbsolutePath(); //tosave is a String

    new CopyFile(selected,tosave);

...the copyFile class will be something like,

public class CopyFile {

    public CopyFile(String srFile, String dtFile) {

        try {
            File f1 = new File(srFile);
            File f2 = new File(dtFile);
            InputStream in = new FileInputStream(f1);

            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            System.out.println("File copied.");
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage() + " in the specified directory.");
            System.exit(0);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Also have a look at this question : How to save file using JFileChooser? #MightBeHelpfull

Community
  • 1
  • 1
COD3BOY
  • 11,964
  • 1
  • 38
  • 56
1

Swing will just give you the location/File object. You are going to have to write the new file yourself.

To copy the file, I will point you to this question: Standard concise way to copy a file in Java?

Community
  • 1
  • 1
Colin D
  • 5,641
  • 1
  • 23
  • 35
0

read the file into a InputStream and then write it out to an OutputStream.

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
user1335794
  • 1,082
  • 6
  • 12
0

If you are using JDK 1.7 you can use the java.nio.file.Files class which offers several copy methods to copy a file to a given destiny.

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205