0

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
4
  • Are you asking for help with Java or Batch? Commented May 20, 2021 at 12:32
  • What do I need to add to the batch file Commented May 20, 2021 at 12:33
  • 1
    Does %1 work? Commented May 20, 2021 at 12:35
  • Do you receive this folderName through the args? Why do you want to use a scripting language via Java when there's java.nio? You could just create a Path that points to the desktop and then resolve the folder name... Commented May 20, 2021 at 12:41

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.