How to check if a File can be created in a Folder before trying to create it in it?

4

My program allows the user to define a Folder, and later the program will create a New File in this Folder.

However, the program is not able to create a file in any folder, for example:

  
  • Creates the new file in the folder normally:
    new FileOutputStream("C:\Users\Public\Documents\novoArquivo.txt");
  •   
  
  • Throws an Exception: java.io.FileNotFoundException: C: \ newfile.txt (Access Denied) :
    new FileOutputStream("C:\novoArquivo.txt");
  •   

I no I'm trying to make the program allow to create Files in any folder, I just need to know with advance (before trying to create the File) if the program will be or not able to create the File in the Folder chosen by the user.

If the user chooses a Folder in which the program is not able to create Files, the user will be warned and will not be able to advance until you choose another Folder.

I thought of using try/catch as if/else to know whether the file can be created or not, putting within that try/catch a new FileOutputStream(pathDaPastaEscolhida); , the problem is that if it does not throw Exception, the file is (without asking the user for confirmation and without giving him the opportunity to choose another folder before actually creating the file).

The file should only be created when the user clicks "Next", and the "Next" button should be disabled until the program is sure to be able to create the file in the folder chosen by the user. >

I've created a compilable sample code to help you get an idea of what I need:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class CriadorDeArquivo {

    public static void main(String[] args) {
        File novoArquivo1 = new File("C:\Users\Public\Documents\novoArquivo.txt");
        criarArquivoSeForPossivel(novoArquivo1); //Cria o Arquivo como esperado

        File novoArquivo2 = new File("C:\novoArquivo.txt");
        criarArquivoSeForPossivel(novoArquivo2); //ERRO: Lança uma Exception ao invés de mostrar a "Mensagem2"
    }

    public static void criarArquivoSeForPossivel(File novoArquivo) {
        if (isPodeSerCriado(novoArquivo)) {
            System.out.println("Com certeza é possível criar o Arquivo neste local, ele será criado..."); //Mensagem0
            criarArquivo(novoArquivo); 
            System.out.println("O Arquivo foi Criado!"); //Mensagem1
        } else {
            System.out.println("O Arquivo não pode ser criado nesse local, escolha outro local."); //Mensagem2
        }
    }

    public static void criarArquivo(File novoArquivo) {
        try {
            new FileOutputStream(novoArquivo); //Cria o Novo Arquivo na Pasta
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static boolean isPodeSerCriado(File arquivo) {
        //O que colocar aqui para determinar se esse arquivo pose ser criado ou não?
        return true;
    }
}
    
asked by anonymous 02.09.2017 / 22:21

1 answer

6

Try using the isWritable() of class Files :

public static boolean isPodeSerCriado(File arquivo) {
    return Files.isWritable(arquivo.toPath());
}

Please note that documentation how to use this method for this purpose:

  

Note that the result of this method is outdated immediately, there is no guarantee that a subsequent attempt to open the file for writing will succeed (or even that it will access the same file). Care must be taken when using this method in security-sensitive applications.

I tested this method with the code below:

File file = new File("C:\TESTEJAVA\test.txt");

System.out.println(Files.isWritable(new File("C:\TESTEJAVA").toPath()));
file.createNewFile();

The folder permissions were as follows:

Theresultwas:

false Exception in thread "main" java.io.IOException: Acesso negado at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(Unknown Source) at othertests.ChecarPermissaoTest.main(ChecarPermissaoTest.java:14)

Until then, the operation of the method is correct, without permission to write or modify, the exception and return false are expected.

After editing the permissions for:

The result was true and the file was successfully created.

I do not know if this method can guarantee in all scenarios whether the folder allows or not to write to it, but by the above test, it is possible to see that it worked correctly.

    
02.09.2017 / 22:25