rmaik
rmaik

Reputation: 1086

How to create a text file inside a specific directory?

I am trying to cretae a file SYS_CONFIG_FILE_NAME inside a specific directory SYS_CONFIG_DIR_NAME. using the below posted code, when i run the java program it creates two directories instead of one directory and one text file inside that directory.

The out put of the below code is

SYS_CONFIG/config.txt. But `config.txt` is not a text file it is just a directory named `config.txt`

i referred also to some question in stackoverflow but i could not find a solution. Please let me know what I am missing?

code:

private final static String SYS_CONFIG_DIR_NAME = "SYS_CONFIG";
private final static String SYS_CONFIG_FILE_NAME = "config.txt";
private static File newSysConfigInstance() throws IOException {

    // TODO Auto-generated method stub
    File f =  new File(SYS_CONFIG_FILE_PATH + "/" + SYS_CONFIG_DIR_NAME + "/" + SYS_CONFIG_FILE_NAME);
    f.mkdirs();
    f.createNewFile();
    return f;
}

Upvotes: 0

Views: 393

Answers (2)

Amrmsmb
Amrmsmb

Reputation: 1

I would do it that way, you have always to call createNewFile() to create a new instance of the file if it is not created.

File dir =  new File(SYS_CONFIG_FILE_PATH, SYS_CONFIG_DIR_NAME);
f.mkdirs(); // this to create the directories need for your path.
File file = new File(dir, SYS_CONFIG_FILE_NAME);
if (file.createNewFile()) {
   system.out.prinln("file first created"); 
   }else {
   // print a message here
   }
   return file;

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533472

You are telling it to make a directory of the form a/b/c if you want a directory of the form a/b then you should give it the directory you want it to create.

File dir =  new File(SYS_CONFIG_FILE_PATH, SYS_CONFIG_DIR_NAME);
f.mkdirs();
return new File(dir, SYS_CONFIG_FILE_NAME);

You don't have to pre-create files before you use them.

Upvotes: 1

Related Questions