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