Pano Pano - 10 days ago 6
Java Question

How do I avoid this java.io.FileNotFoundException?

When I enter the full file path (C:\Users\djustinwebb\Documents\BlueJ Projects\LightHouse) for "search" and it attempts to open the file I get the error:
java.io.FileNotFoundException: C:\Users\djustinwebb\Documents\BlueJ Projects\LightHouse (Access is denied) (in java.io.FileInputStream)

I have input "invoicedata.txt" for search and it worked even though it doesn't read through the file properly but I would like to know why it won't work when I use the full file path. What do I need to do to use the full file path without running into this error?

public String searchCase()throws FileNotFoundException
{
String fileLine = null;

StringTokenizer stok = null;

Scanner inputFile = new Scanner(new File(search));


String whatever = null;



while(inputFile.hasNextLine())
{
fileLine = inputFile.nextLine();
stok = new StringTokenizer(fileLine,",");

caseLCount++;

while(stok.hasMoreTokens())
{
if(userWord.equals(stok.nextToken()))
{
caseWCount++;

whatever += caseLCount + ".\n";
}//end if
}// end nested while
}//end outer while
inputFile.close();
return whatever;
}// end searchCase()

Answer

This happens because you are trying to open and read a directory, which is LightHouse here. You are supposed to enter the file name in the file path as well, like this, ..\LightHouse\invoicedata.txt.

If you want to distinguish between files and folders, use the isFile() and isDirectory() methods. You can get the contents of folders using the list() and listFiles() methods.