Search code examples
javabatch-filebatch-rename

Pass variable from Java to Batch


This Java programm opens a Batch file and passes the string folderName

public class FolderCreator {

    public static void main(String[] args) {
        try{    
            Process p = Runtime.getRuntime().exec("C:/Documents/NameFolder.bat folderName");
            p.waitFor();
        }catch(Exception e) {
            System.out.println(e);
        }   
    }
}

This is the NameFolder.bat file. It shall create a folder with the name from the passed Java variable above.

//What do I need to ad here?

if not exist "C:\Desktop\folderName\" mkdir C:\Desktop\folderName

What do I need to add to the Batch file?

EDIT:

This works

if not exist "C:\Desktop\%1\" mkdir C:\Desktop\%1

Solution

  • Batch Script

    The following will create a directory only if that directory does not exist

    if not exist "C:\Users\%USERNAME%\Desktop\%1" (
      mkdir  "C:\Users\%USERNAME%\Desktop\%1"
    )
    

    Assuming you save this to file C:/Documents/NameFolder.bat you just execute it with the same exact Java code

    Process p = Runtime.getRuntime().exec("C:/Documents/NameFolder.bat folderName");
    

    This will create a c:\Users\%USERNAME%\Desktop\folderName directory only if that directory doesn't already exist.

    This is not best practice. Please read up on executing shell/batch scripts from Java