Как я могу сделать каталог на 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++;
    }

1 ответ

Решение

Попробуйте сделать это в два этапа. Сначала позвоните 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) {
}
Другие вопросы по тегам