public void readItemData()
{
try {
Frame frame = null;
FileDialog fileBox = new FileDialog(frame ,"Open", FileDialog.LOAD);
fileBox.setVisible(true);
String filename = fileBox.getFile();
System.out.println(filename);
File inFile = new File("filename");
System.out.println(inFile.getAbsolutePath());
Scanner fileScanner = new Scanner(inFile);
while ( fileScanner.hasNext() )
{
String line = fileScanner.next();
System.out.println(line);
}
}
catch (FileNotFoundException ex)
{
System.out.println("Error.");
}
}
The above code is supposed to take a file given by the file dialog box, then pass it to a scanner which reads the whole file. The system to take the file is working, but when passed to the scanner it always gives a file not found exception. I'm not sure how to pass it properly to the scanner and simply read line by line.
I tried using quotations marks and not, removing the try-catch, etc. I feel like it is a simple problem but I cant figure it out. There have been instances where I got it to print the name of the file, but I think that was when I passed it in quotations and it was reading as if it was a string.
The
FileDialog.getFile()method only gives you the filename. You need to also callgetDirectory()to get the directory of the file. It's likely that you were trying to get a file from a different directory than what the user selected.Instead of calling
getDirectory()andgetFile()and putting them together, it would be easier to callgetFiles(). This returns an array ofFile- it's an array because the user may have selected more than one file. If the user pressed Cancel, an empty array would be returned.So you can do this: