javadirectoryexternal-sorting

How can I make a directory in Java?


I am trying to create a new file directory, but the function mkdir() doesn't work, neither mkdirs().

Here's my code:

...
  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++;
    }
...

Edit: I made the edits and now it's working!

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

Solution

  • Try doing this in two steps. First, call File.mkdirs() to create the entire directory structure, if necessary, then create the file you pass to the 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) {
    }