Create a folder with a given name

Asked

Viewed 285 times

2

I’m trying to create a folder with a certain name but I don’t know why it always appears bin+name.

Example: If secondArg = dot then the folder name becomes bindot.

Is it because I’m running in the terminal? Since when I run in the terminal I have to go to the project folder and then to the bin in order to run the class. How can I solve?

private void makeDir(String secondArg) {
        File theDir = new File(System.getProperty("user.dir") + secondArg);

        // if the directory does not exist, create it
        if (!theDir.exists()) {
            System.out.println("creating directory: " + theDir.getName());
            boolean result = false;

            try{
                theDir.mkdir();
                result = true;
            } 
            catch(SecurityException se){
                //handle it
            }        
            if(result) {    
                System.out.println("Repository " + theDir.getName() + " was been created");  
            }
        }

    }
  • Where your folder should be created?

  • In the project folder where the bin and src @Felipemarinho folders are located

1 answer

1

Missing a folder separator:

private void makeDir(String secondArg) {
        File theDir = new File(System.getProperty("user.dir") + File.separator + 
 secondArg);

        // if the directory does not exist, create it
        if (!theDir.exists()) {
            System.out.println("creating directory: " + theDir.getName());
            boolean result = false;

            try{
                theDir.mkdir();
                result = true;
            } 
            catch(SecurityException se){
                //handle it
            }        
            if(result) {    
                System.out.println("Repository " + theDir.getName() + " was been created");  
            }
        }

 }

I used File.separator instead of bars(\ or /) because this is the responsibility of the running operating system to define.

  • So keep in bin folder. I wanted it to be in the folder of my project where the bin and src @diegofm folders are located

  • @Rafael anyway this fix is required in your code. Ta using eclipse?

  • Yes, I am creating a client-server that if the client enters a certain command the server must create a folder with the name given by the client. I can’t use eclipse to run @diegofm

  • @Rafael but your application will run from the eclipse? Because it doesn’t make much sense to configure to open in the project folder, and after you generate the jar, the reference will be lost. Run a test, generate the jar or copy the file suaClasse.java and run via cmd. It will work right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.