3

I have an aplicattion that needs to create a folder to unzip some files, but I want to pass a file path that my application could run, create and save my files in any OS, but I don't know what should be the output Path to do that.

for example:

File folder = new File(outputFolder);
if (!folder.exists()) {
    folder.mkdir();
}

What path should I use in outputFolder to create my folder in Documents/UnzipTest in any Operation System (Windows, mac or linux)?

Yurets
  • 3,999
  • 17
  • 54
  • 74
Victor Laerte
  • 6,446
  • 13
  • 53
  • 102
  • Check out [this](http://stackoverflow.com/a/3548818/645270) answer, and the one below. It should help. (I think the one below is more helpful) – keyser Jan 27 '13 at 21:01

5 Answers5

6
System.getProperty("user.dir");

Or if you're using Java 7

Filesystems.getDefault();

will give you the base directory from which to work.

2

Use java.io.File#separator :

String userHome = System.getProperty("user.home");
String outputFolder = userHome + File.separator + "dir1";
File folder = new File(outputFolder);
if (!folder.exists()) {
   folder.mkdir();
}
isvforall
  • 8,768
  • 6
  • 35
  • 50
1

I would define a property (in some external properties file, for example) for the root folder, so user can define what is the root folder after the setup or during the installation for all your operations.

Other option is to use user folder (aka home folder) as this root folder (or if above property is not defined), defined in system property user.dir. Or use folder where your application is installed - you can find it e.g. by finding some resource in application jar and then parsing path from returned URL.

With root folder defined, you can use constructor new File(rootFolder, outputFolder); where you can simply use slashes for the path in outputFolder (e.g. /foo/bar). Such path would work for all OSes.

igr
  • 10,199
  • 13
  • 65
  • 111
1

You can use Commons IO from Apache Commons with the classes FileUtils and FilenameUtils.

If you use in your application the UNIX style for your paths, you can transform the path to SO style with the method:

org.apache.commons.io.FilenameUtils.separatorsToSystem(String)

If you want create a directory only if not exists:

org.apache.commons.io.FileUtils.forceMkdir(File)

May you have a path to the directory and may you need a new folder in this directory, you can cancatenate using the method for get the full path:

org.apache.commons.io.FilenameUtils.concat(String, String)

The path returned path is always normalized, contain separators in the format of the system.

May you need the user directory path:

org.apache.commons.io.FileUtils.getUserDirectory()
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
0
String outputFolder = System.getProperty("user.home") + File.separator + "Documents" + File.separator +"TestandoUnzip";

The code that I needed. Thanks guys.

Victor Laerte
  • 6,446
  • 13
  • 53
  • 102