KrackLocks
KrackLocks

Reputation: 13

Check for a file before the program loads

The idea is to create a home screen that loads required information out from a text file. The application looks for the file, and if it is not found it asks for the file path.

so far i have this code

    BufferedReader br;

    try{
        br = new BufferedReader(new FileReader(principal));
    }catch(FileNotFoundException e){
        while(!principal.contains(".INICIO")){
            JOptionPane.showMessageDialog(this, "Not a valid file paht", "error",JOptionPane.ERROR_MESSAGE);
            JFileChooser archivo = new JFileChooser("Seleccione el archivo principal");
            principal = archivo.getSelectedFile().getPath();
        }
    }

After that i want the program to try again with the new file path. I'm thinking something along the lines of:

   while(condition){
       try{
           br = new BufferedReader(new FileReader(principal));
       }catch(Exception e){
           //some code here
       }
   }

but i dont know what the "condition" is. Any suggestions?

Upvotes: 0

Views: 29

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

This comes down to a number of work flows. If you're only interested in know if the file that the user has selected exists you could do something like...

JFileChooser archivo = new JFileChooser("Seleccione el archivo principal");
int action = archivo.showOpenDialog(null);
File principal = archivo.getSelectedFile();
while (action != JFileChooser.CACNEL_OPTION && !principal.exists()) {
    JOptionPane.showMessageDialog(this, "Not a valid file paht", "error",JOptionPane.ERROR_MESSAGE);
    action = archivo.showOpenDialog(null);
    principal = archivo.getSelectedFile();
}

if (!action == CACNEL_OPTION) {
    // File reference should now be valid, open and read away...
}

Now, if you also want to know if the file was valid, you would need to read it. About this point, I would create a method that could prompt the user for a File and which could return null if they selected Cancel, this way you can better control the flow...

Upvotes: 1

Related Questions