I am using Eclipse and the Java Library: java.io.FileInputStream;
My script cannot find a file that I want to assign to a variable using the constructor FileInputStream even though the file is in the Working directory.
Here is my code:
package login.test;
import java.io.File;
import java.io.FileInputStream;
public class QTI_Excelaccess {
public static void main(String [] args){
//verify what the working directory is
String curDir = System.getProperty("user.dir");
System.out.println("Working Directory is: "+curDir);
//verify the file is recognized within within the code
File f = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
if (f.exists() && !f.isDirectory()){
System.out.println("Yes, File does exist");
} else {
System.out.println("File does not exist");
}
//Assign the file to src
File src = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
System.out.println("SRC is now: "+src);
//Get Absolute Path of the File
System.out.println(src.getAbsolutePath());
FileInputStream fis = new FileInputStream(src);
}*
My output is (when i comment out the last line) is
"Working Directory is: C:\Users\wes\workspace\QTI_crud Yes, File does exist SRC is now: C:\Users\wes\workspace\QTI_crud\values.xlsx C:\Users\wes\workspace\QTI_crud\values.xlsx"
When I don't comment out the last line, I get the error:
"Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type FileNotFoundException
at login.test.QTI_Excelaccess.main(QTI_Excelaccess.java:30)"
Where have I gone wrong in my code? I'm pretty new to Java
Much thanks!
Major problem with the code is that you after you know that file do not exist on specified directory, you tried to read the file. Hence, it is giving you the error.
Refactor it to this
if (f.exists() && !f.isDirectory()){
System.out.println("Yes, File does exist");
try {
FileInputStream fis = new FileInputStream(f);
//perform operation on the file
System.out.println(f.getAbsolutePath());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("File does not exist");
}
Here as you can see, if file exists then you try to read the file. If it is not available you don't do anything.