Java创建目录和子目录(如果不存在)

huangapple go评论65阅读模式
英文:

Java create directory and subdirectory if not exist

问题

假设我想创建一个名为generatedAnswers的目录,其中包含另一个名为dirName的目录,这是我输入的一个字符串变量。

然后,我想要将fileName插入到目录generatedAnswers/dirName,使得文件按照以下结构位于dirName目录中:

/ generatedAnswers
   /dirName
     fileName.txt

我尝试了以下代码,但它不起作用:

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

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

我得到的结果是:

/generatedAnswers
  dirNamefineName.txt(这变成了文件名)

我做错了什么?

英文:

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?

答案1

得分: 1

我认为你可以使用这段代码:

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

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

我添加了 file.getAbsolutePath(),因为你试图获取文件路径。

英文:

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

答案2

得分: 0

尝试这个方法:

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

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

答案3

得分: 0

你在代码中做错的地方在于这行:

file.getParentFile().mkdirs();

file 的路径是 generatedQuestions/dirName,所以 file.getParentFile() 返回的是 generatedQuestions,然后你在其上调用了 mkdirs(),因此你只创建了一个名为 generatedQuestions 的目录,而没有创建子目录 dirName。移除 getParentFile(),即只保留以下部分:

file.mkdirs();

需要注意的是,mkdirs() 可能会失败,如果失败的话会返回 false。你应该检查返回值,不要假设它总是成功的。

最后,PrintWriter 构造函数的参数也是错误的。类 java.io.FiletoString() 方法不会打印尾部的分隔符字符,所以你需要添加它,即:

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

以下代码对我有效:

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()' 失败。");
}

或者,你可以使用接口 Path 和类 Files 的组合,如下所示:

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();
}
英文:

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();
}

huangapple
  • 本文由 发表于 2020年10月17日 18:16:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64401340.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定