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

Asked

Viewed 1,186 times

4

My program allows 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 New File in Folder Normally:
    new FileOutputStream("C:\\Users\\Public\\Documents\\novoArquivo.txt");

  • Casts an Exception: java.io.Filenotfoundexception: C: newFile.txt (Access denied):
    new FileOutputStream("C:\\novoArquivo.txt");

I nay I am trying to make the program have permission to create Files in any folder, just need to know with advance (before trying to create the File) whether or not the program will be able to create the File in the Folder chosen by the user.

If the user chooses a Folder in which the program is unable to create Files, the user will be notified immediately and will not be able to proceed until he chooses another Folder.


I thought I’d use one try/catch as if/else to know if the File can be created or not, placing inside this try/catch one new FileOutputStream(pathDaPastaEscolhida);, the problem is that if Do Not Launch Exception, the File is immediately created (without asking for confirmation from the user and without giving him the opportunity to choose another Folder before effectively 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 that it is able to create the File in the Folder chosen by the user.


I created a compileable 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;
    }
}

1 answer

6


Try to use the method isWritable() class Files:

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

It is worth mentioning the reservation of documentation as to the use of this method for this purpose:

Note that the result of this method is immediately outdated, 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 should be taken when using this method in safety sensitive applications.


I did a test with 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:

inserir a descrição da imagem aqui

The result was:

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 record or modify, the exception and the return false are expected.

After editing permissions for:

inserir a descrição da imagem aqui

The result was true and the file was created successfully.

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

  • I had already tried this method, but it always returns false because it checks if the File already exists, as described in the documentation: return true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise.; I mean, it doesn’t work to check if I can create a file, only works to check if I can overwrite an existing file.

  • @Douglas see the issue, try it with her.

  • System.out.println(new File("C:\\").canWrite()); returned true instead of returning false. That is, he says that "you can write in C:" but when creating a file in "C:" he launches an Exception.

  • @Douglas I edited the answer, try with edited code, this previous solution was quite flawed even.

  • Files.isWritable(new File("C:\\Users\\Public\\Documents\\").toPath()); returned true correctly and Files.isWritable(new File("C:\\").toPath()); returned false correctly. It looks like this will solve the problem, I will do more tests later and I accept your reply if you confirm. Thank you very much.

  • isPodeSerCriado - I don’t know if you killed the Portuguese language or the English language with this. Maybe both. However, keep my +1 anyway. :)

  • @Victorstafusa I just copied the method in the question code, I thought to comment, but I was afraid of sinning for excess of preciousness in fixing it.

  • 1

    @Sorry, I read the question in a hurry, because it was already answered.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.