1

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

Amundeep Singh
  • 194
  • 5
  • 16

4 Answers4

1

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();
}
fge
  • 119,121
  • 33
  • 254
  • 329
C. Reed
  • 2,382
  • 7
  • 30
  • 35
1

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

fge
  • 119,121
  • 33
  • 254
  • 329
1

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.
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
-1

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

new File("new-dir").mkdir();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130