1

So I am using eclipse to make this application. I've been searching for some kind of code or script to let the user select the file directory to put the file that is about to be downloaded. What I am wanting it to do is ask the user to select the directory to place this file and then the download starts. I know about Jfilemover but I don't think that can do it for me. Any ideas or points in the right direction I will appreciate.

Zach Suggs
  • 13
  • 2

1 Answers1

0

Not sure what you actually want. Anyway try this:

import javax.swing.*;
import java.net.*;
import java.io.*;
import java.nio.file.*;

public class FileChooserExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFileChooser chooser = new JFileChooser();
                int option = chooser.showSaveDialog(null);
                if (option == JFileChooser.APPROVE_OPTION) {
                    File file = chooser.getSelectedFile();
                    download(file);
                } else
                    System.out.println("No file was selected.");
            }
        });
    }

    static void download(File dest) {
        try {
            URL url = new URL("http://stackoverflow.com");
            Files.copy(url.openStream(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("done");
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}
tonychow0929
  • 458
  • 4
  • 10
  • and similar post here: http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java – tonychow0929 Mar 01 '15 at 06:22
  • What I am trying to do is when you press a button on the appframe it ask where the file should go then after they select it the download starts. – Zach Suggs Mar 01 '15 at 06:36
  • then you register an ActionListener on the button, override the method actionPerformed(ActionEvent e) and show the chooser – tonychow0929 Mar 01 '15 at 06:38
  • Also I have separate java files that deal with downloading another that handles the Buttonlistener itself its all not in one .java file. – Zach Suggs Mar 01 '15 at 06:38