mkodad
mkodad

Reputation: 43

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 the runtime interface, there is a command to create a folder named eg "My Folder", with a space

For create the Unix command is easy to do either: mkdir My\ Folder or mkdir "My Folder"

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

Here is 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's still not working,

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

Are there solutions?

Thank you !

Upvotes: 3

Views: 2219

Answers (3)

Stephen C
Stephen C

Reputation: 718886

The other answers have explained how to do put spaces in directory names. I want to try and convince you NOT to do this at all.

By convention, pathnames on Linux don't have spaces in them. Sure the file system allows this, and so on. But it makes life awkward for the Linux user:

  • When entering pathnames with spaces from the command prompt, you always have to remember to quote them or escape the spaces.

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

Combine these, and you will find that your pretty directory names with spaces in them are actually a nuisances ... or worse.

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

  • use something like URL-style percent-encoding to encode the filenames, so that the space characters are not represented as spaces in the actual pathnames in the file system, or
  • store the user-supplied names in a database.

Upvotes: 2

Philipp Claßen
Philipp Claßen

Reputation: 43979

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

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74048

It is a lot easier to use File.mkdir() for that

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

Upvotes: 4

Related Questions