nTuply
nTuply

Reputation: 1374

Java create directory and subdirectory if not exist

Let's assume I want to create the generatedAnswers directory which contains another directory dirName which is a String variable I input.

Then I want to insert fileName in the directory `generatedAnswers/dirName" such that the file falls in the dirName directory as per the following structure:

/ generatedAnswers
   /dirName
     fileName.txt

I tried the following code but it does not work:

File file = new File("generatedQuestions/"+dirName+"/");
file.getParentFile().mkdirs();

PrintWriter writer = new PrintWriter(file+fileName+".txt");

The result I'm getting is: /generatedAnswers dirNamefineName.txt (this turned into the filename)

What am I doing wrong?

Upvotes: 0

Views: 1923

Answers (3)

Abra
Abra

Reputation: 20924

What you are doing wrong is in this line of your code:

file.getParentFile().mkdirs();

The file path is generatedQuestions/dirName, so file.getParentFile() returns generatedQuestions and you call mkdirs() on that, hence you are only creating directory generatedQuestions and not the sub-directory, dirName. Remove the getParentFile(), i.e. just

file.mkdirs()

Note that mkdirs() may fail, in which case it will return false. You should check the return value and not assume that it always succeeds.

Finally the argument to PrintWriter constructor is also wrong. The toString() method of class java.io.File does not print the trailing separator character so you need to add that, i.e.

PrintWriter writer = new PrintWriter(file + File.separator + fileName+".txt");

The following code worked for me.

String dirName = "dirName";
File file = new File("generatedQuestions" + File.separator + dirName);
if (file.mkdirs()) {
    String fileName = "fileName";
    try (PrintWriter writer = new PrintWriter(file + File.separator + fileName+".txt")) {
    }
    catch (FileNotFoundException x) {
        x.printStackTrace();
    }
}
else {
    System.out.println("'mkdirs()' failed.");
}

Alternatively, you could use a combination of interface Path and class Files like so.

Path path = Paths.get("generatedQuestions", dirName);
try {
    Files.createDirectories(path);
    path = path.resolve(fileName + ".txt");
    PrintWriter writer = new PrintWriter(path.toFile());
}
catch (IOException x) {
    x.printStackTrace();
}

Upvotes: 0

evgzabozhan
evgzabozhan

Reputation: 150

I think you can use this code :


File file = new File("generatedQuestions/"+dirName+"/");
file.getParentFile().mkdirs();

PrintWriter writer = new PrintWriter(file.getAbsolutePath() +fileName+".txt");

I add file.getAbsolutePath(), because u try get file path

Upvotes: 1

Couper
Couper

Reputation: 434

Try this way:

String dirName = "someDirectory";
String fileName = "file.txt";
File file = new File("generatedQuestions/" + dirName + "/" + fileName);
if(file.getParentFile().mkdirs()) {
    PrintWriter printWriter = new PrintWriter(file);
}

Upvotes: 0

Related Questions