1

I'm kinda new in Java and even more in batch, I'm working on a little program that auto check bunch of specific files in a folder, however at this point, I need to use a Scanner in Java to read the path of the folder I want to check and I wonder what would I need to just have to drag and drop the folder into my batch to execute this application

Here is the start of my application with the scanner

public static void main (String[] args) {
        System.out.print("Locators folder : ");
        Scanner sc = new Scanner(System.in);
        String path = sc.next();
        sc.close();
        File[] folders = new File(path).listFiles();

And here is the batch even if it won't bring much info

@ECHO off

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" -jar "E:\Hugo\Documents\_Quadrica\afc.jar"
  • 1
    Could you elaborate on "drag and drop the folder into my batch"? Do you mean you want to drag a folder in desktop GUI and drop it on .jar file in order to run in? – matvs Jun 19 '20 at 07:17
  • Yes kinda, in the windows explorer, I would like to drag a folder, drop it into the batch file (Also in Windows explorer) that run my jar file – H_T_Bernard Jun 19 '20 at 07:24

1 Answers1

1

You don't need a Scanner to get the path.
When you drag a file (or folder) onto your batch file, it becomes a command line argument to your batch file, so all you need to do is add %1 to the end of the java command in the batch file, i.e.

"C:\Program Files\Java\jdk-13.0.2\bin\java.exe" -jar "E:\Hugo\Documents\_Quadrica\afc.jar" "%1"

Note: Enclose %1 in double quotes is necessary if the path contains spaces. Also note that it will not work if the path contains unusual characters like &, for example. Please refer to Batch file Copy using %1 for drag and drop

Then in your java code, the path is actually in the args parameter to method main(), so your java code should be...

public static void main (String[] args) {
    if (args.length > 0) {
        System.out.println("Locators folder: " + args[0]);
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41
  • You should use `"%~1"` rather than `"%1"`, since paths including spaces already arrive quoted, and the `~` removes them at first, so you avoid quoting an already quoted path… – aschipfl Jun 19 '20 at 12:02
  • @aschipfl Or simply drop the double quotes since they are unnecessary? – Abra Jun 19 '20 at 12:04
  • No, since they protect spaces and some special characters… – aschipfl Jun 19 '20 at 13:02