1

I want to upload a file into a local folder (on my PC). The user should select a file. Than this file should be loaded into a folder (this folder is hard coded in my Java class). Unfortunately I didn't find a good solution for this. I just found something about a JFileChooser which is nice to open a file, but not to load one.

public static void main(String[] args){
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "JPG & GIF Images", "jpg", "gif");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
        System.out.println("You chose to open this file: " +
                chooser.getSelectedFile().getName());
    }
}

Is it possible to just give the file chooser access to a specific folder? the folder is hard coded like this:

public static String uploadPath = System.getProperty("user.dir") + "/uploads Modul1";
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
CodeIsLaw
  • 307
  • 2
  • 13
  • Upload a file - from where? Usually people say "upload" when they want to copy data to a remote system using the network. `JFileChooser` shows you the local file system, not the remote, so what do you want to do exactly? – Joni Aug 12 '20 at 12:37
  • right, I want to copy a file and move it into an other directory (all on the same computer). But I am not sure if this is possible with the FileChooser @Joni – CodeIsLaw Aug 12 '20 at 12:44

1 Answers1

1

Copying or moving files is independent of how the file is chosen. The easy way to copy a file is with the Files.copy method. Here's how you can add it to your existing code:

    int returnVal = chooser.showOpenDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
        File selectedFile = chooser.getSelectedFile();
        System.out.println("You chose to copy this file: " +
            selectedFile.getName());

        Path newPath = Paths.get(uploadPath, selectedFile.getName());
        Files.copy(selectedFile.toPath(), newPath);
    }

The official tutorial has a section on copying files: https://docs.oracle.com/javase/tutorial/essential/io/copy.html

If you want to move the file instead of copying it, use Files.move instead of Files.copy.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • Thanks for your help, Do you know if it is possible to allow just a specific path? I don't want that the user gets access to the whole file system, can I block some paths? – CodeIsLaw Aug 12 '20 at 13:26
  • 1
    Yes the solution is to set a custom "file system view" for JFileChooser. You can find a complete implementation in https://stackoverflow.com/questions/32529/how-do-i-restrict-jfilechooser-to-a-directory or here https://stackoverflow.com/questions/8926146/jfilechooser-want-to-lock-it-to-one-directory – Joni Aug 12 '20 at 13:35