0

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;
}
0

2 Answers 2

1

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.

1
  • 2
    i think you forgot "f.createNewFile();" before the return statement and after .mkdirs()
    – Amrmsmb
    Dec 12, 2014 at 15:55
0

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.