如何在 Java 中创建目录?

How can I make a directory in Java?

我正在尝试创建一个新的文件目录,但是函数 mkdir() 不起作用,mkdirs()

这是我的代码:

...
  while (leitor.hasNext()){
      String [] plv = LerPalavras(tamMem, leitor);
      Arrays.sort(plv);
      String nomeTemp = "/temp/temp" + contador + ".txt"; // I need to create this directory
      try{
        escritor = new FileWriter(nomeTemp);
        for (int i = 0; i < tamMem; i++) {
          escritor.write(plv[i] + " ");
        }
        escritor.close();
      } catch (IOException e){
        System.out.println(e.getMessage());
      }
      contador++;
    }
...

编辑:我进行了编辑,现在可以使用了!

File pastaTemp = new File("/temp/temp");
    pastaTemp.mkdirs();

    while (leitor.hasNext()){
      String [] plv = LerPalavras(tamMem, leitor);
      Arrays.sort(plv);
      File arqTemp = new File (pastaTemp, contador + ".txt");
      try{
        escritor = new FileWriter(arqTemp);
        for (int i = 0; i < tamMem; i++) {
          escritor.write(plv[i] + " ");
        }
        escritor.close();
      } catch (IOException e){
        System.out.println(e.getMessage());
      }
      contador++;
    }

尝试分两步进行。首先,调用 File.mkdirs() 创建整个目录结构,如有必要,然后创建传递给 FileWriter 的文件:

try {
    File folder = new File("/temp/temp");
    folder.mkdirs();
    // then create a file object at this location
    File file = new File(folder, contador + ".txt");

    escritor = new FileWriter(file);
    // the rest of your code
}
catch (Exception e) {
}