rookProgrammer
rookProgrammer

Reputation: 27

How to check if a file exists in java

Im having a problem in checking if a file exists in Java. However the IF block seems to work , but the ELSE seems dont. see, when a file exist, it will prompt a box that says, 'File found.' which happens in my program whenever a file do exist, the problem is errors flood in my console when a file dont exist. Can somebody tell me what's the easier and shorter way of coding my problem? thanks ! here's my code

        public void actionPerformed(ActionEvent e) {
             BufferedReader br = null;
             File f = new File(textField.getText());
             String path =  new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
            try {

                String sCurrentLine;

                br = new BufferedReader(new FileReader(path+f));
                if (f.exists())
                {
                    JOptionPane.showMessageDialog(null, textField.getText()+" found" );
                    while ((sCurrentLine = br.readLine()) != null) {

                         textArea.append(sCurrentLine);
                         textArea.append(System.lineSeparator());
                    }
                }
                else
                {
                    JOptionPane.showMessageDialog(null, textField.getText()+" not found" );
                }


            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (br != null)
                    {

                        br.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

    }


    });

Upvotes: 1

Views: 5008

Answers (4)

M A
M A

Reputation: 72844

The problem is with this line:

br = new BufferedReader(new FileReader(path+f));
  1. You're appending a File to a String, which doesn't make sense. You should append a String to a String, in this case textField.getText()) appended to path.

  2. This line will throw an exception if the file doesn't exist as per the documentation of FileReader:

Throws: FileNotFoundException - if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.

This causes your program to reach the catch clause and print an exception stack trace. You should only call this line when f.exists() returns true:

if (f.exists())
{
    br = new BufferedReader(new FileReader(path + textField.getText()));
    ...
}

Upvotes: 2

Stefan
Stefan

Reputation: 1

You have to instantiate the BufferedReader after checking the existence of the file.

String path =  new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
File f = new File(path + textField.getText());
...
if (f.exists())
{
    br = new BufferedReader(new FileReader(f.getAbsolutePath()));  // or br = new BufferedReader(f);
    ...

Upvotes: 0

Xirema
Xirema

Reputation: 20396

String path = "C:\\Path\\To\File\\Directory\\";
String fileName = "NameOfFile.ext";
File f = new File(path, fileName);
if(f.exists()) {
    //<code for file existing>
} else {
    //<code for file not existing>
}

Upvotes: 0

Holger
Holger

Reputation: 298143

Look at these lines of your code:

br = new BufferedReader(new FileReader(path+f));
if (f.exists())

You are trying to open the file before checking whether it exists. So if the attempt to open it fails with a FileNotFoundException, the test is never reached.

Upvotes: 1

Related Questions