Question

I've created a program to upload images from one device to another. As it stands, the program only allows the user to upload one file at a time. If I wanted to edit the program to allow the user to upload several files at once, what would be the best way of doing it.

String source1 = source.getSelectedFile().getPath();
System.out.println("Source1: " + source1);
String nwdir1 = nwdir.getSelectedFile().getPath() + "\\" + filename;
System.out.println("nwdir1: " + nwdir1);

Path source = Paths.get(source1);
Path nwdir = Paths.get(nwdir1);

try {
    Files.copy(source, nwdir);

I've noticed you can do .getSelectedFiles(), but as that doesn't allow .getPath() im unsure how to continue. Assuming you can do this:

File[] source1 = source.getSelectedFiles();

How would I go about doing the second line:

String nwdir1 = nwdir.getSelectedFile().getPath() + "\\" + filename;

When I replace the line with the File array (shown above), I get an error on lines:

Path source = Paths.get(source1);
Path nwdir = Paths.get(nwdir1);
Was it helpful?

Solution

File.listFiles or File.listFiles(FileFilter)

Multi file selection

Sorry, that's what I thought you wanted, but you're using the JFileChooser to select a directory so I assumed you want to do a directory listing :P

Set the JFileChooser to allow multiple selections using setMultiSelectionEnabeld. You'll probably want to set the file selection mode to JFileChooser.FILES_ONLY or JFileChooser.FILES_AND_DIRECTORIES if you still want them to be able to select directories.

You will probably also want to set the file filter to allow the dialog to filter the directories contents, restricting what the user can select, for simplicity sake, take a look at FileNameExtensionFilter

UPDATED

JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "png", "jpg", "jpeg");
chooser.setFileFilter(filter);

switch (chooser.showOpenDialog(null)) {

    case JFileChooser.APPROVE_OPTION:

        String currentPath = chooser.getCurrentDirectory().getPath();
        File[] files = chooser.getSelectedFiles();

        if (files.length > 0) {

            System.out.println("You have choosen " + files.length + " from " + currentPath);

        } else {

            System.out.println("You didn't selected anything");

        }

        break;

}

OTHER TIPS

Use FileUtils from apache commons library. Very powerful and useful. You can even specify which file formats you want to copy etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top