How to create a folder with spaces written in Java under Linux?

I have a serious problem

I want to run a Linux command using a Java class with a runtime interface, there is a command to create a folder named "My folder" with a space

To create a Unix command it is easy to run: mkdir My \ Folder or mkdir "My Folder"

But how to translate this to Java, I tried with two commands: Runtime.exec ("mkdir My \ Folder") Runtime.exec ("mkdir \" My folder \ "")

Here's an example:

import java.io.IOException;
public class CreerDossier {
    public static void main(String[] args) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        runtime.exec("mkdir My\\ Folder");
        runtime.exec("mkdir \"My Folder\"");
    }
}

      

But it still doesn't work,

For runtime.exec ("mkdir My \ Folder") it creates two folders My \ and Folder For runtime.exec ("mkdir \" My Folder \ "") it also creates two folders "My Folder"

Are there solutions?

Thank!

+3


source to share


3 answers


runtime.exec(new String[] { "mkdir", "My Folder" });

      



+1


source


Much easier to use File.mkdir()

for this



File dir = new File("My Folder");
dir.mkdir();

      

+4


source


Other answers explain how to create spaces in directory names. I want to try to convince you NOT to do this at all.

By convention, Linux pathnames do not contain spaces. Of course, the filesystem allows this and so on. But this makes life inconvenient for a Linux user:

  • When entering paths in spaces from the command line, you should always remember to quote them or avoid spaces.

  • When writing shell scripts where path names are stored in variables, you must be careful when there are / might be spaces in the path. If you don't, the scripts are likely to break.

Combine them and you find that your pretty directory names with spaces in them are actually a nuisance ... or worse.

My advice would be to redesign your system to avoid this. Either don't let the user of your system put spaces in the names in the first place, or (if you need to support this because it is a REQUIREMENT) then:

  • use something like percent-encoded URL-style to encode filenames so that whitespace characters are not represented as spaces in valid file system pathnames, or
  • save usernames in the database.
+2


source







All Articles