Amundeep Singh
Amundeep Singh

Reputation: 194

How to create a folder in the root directory of my Java application?

Is there a way to create a folder (with a specific name) in the main directory of my Java app. I have a user system in my game, and whenever a new user is created, I want it to create a folder that will store all there progress in (and the folder name should be the name they put in).

For example:

From this:

enter image description here

To this (just by entering a username in the game):

enter image description here

Upvotes: 1

Views: 6145

Answers (4)

C. Reed
C. Reed

Reputation: 2452

From this forum:

File f = new File("TestDir");
try{
  if(f.mkdir())
    System.out.println("Directory Created");
  else
    System.out.println("Directory is not created");
}catch(Exception e){
  e.printStacktrace();
}

Upvotes: 1

fge
fge

Reputation: 121702

Define the "main directory of your Java app"? There is no such beast.

You want to be very careful when doing things like this, for security concerns. Best to define a directory in a property file and use that as a base directory for your application. Then, as already said, it is just a use of .mkdir{,s}() to achieve what you want.

And @C.Reed also rightly says that you should check for mkdir()'s return value: Java's File API is hugely flawed in that it will not throw an exception when directory/file creation/move will fail. Fortunately, Java 1.7 will cure that with its new APIs.

(an example I encountered is seeing code which would fail to .move() a file around: the problem is that it worked on the dev's machine, but on the production machine the directory was to be moved on another filesystem --> havoc)

Hint: use Apache's commons-io

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168815

Establish a directory inside a sub-directory1 of a known and reproducible path2.

  1. E.G. a directory structure based on the package name of the main class - this helps avoid collisions with other apps.
  2. A good place is user.home - which should be a directory that the game can read from and write to.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533462

If the main directory is the working direct of your application you can create a directory with

new File("new-dir").mkdir();

Upvotes: -1

Related Questions