Reputation: 43
I have a simple program that checks if my file exists.
I've copied the file under my work folder (with my java classes) and in c:.
when calling
, the code generats an exception error!new FileInputStream("1.xls")
Exception in thread "main" java.io.FileNotFoundException: 1.xls (Le fichier spécifié est introuvable)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at NewMain.main(NewMain.java:25)
when calling it with
, it works!new FileInputStream("c:\\1.xls")
Here is my code
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
InputStream input = new BufferedInputStream(new FileInputStream("c:\\1.xls"));
System.out.print("The file exists");
}
Upvotes: 4
Views: 4950
Reputation: 208944
I've copied the file under my work folder (with my java classes)
This "1.xls"
is a relative path. When running in development in your IDE (reading from the file system) the path will be relative to the working directory, which is generally the project root. So your file (given that relative path) will have to be in the directly in the project root, the same level as the src
If running from command like and the working directory is the where the class is, and the file is where the class is, then that should also work with the path you're using
when calling it with new FileInputStream("c:\1.xls"), it works!
Yes it should work. generally absolute paths should work
Note: The fact that you're placing the file where the Java class is, tells me that you want the file to be embedded as a resource to your project. In that case, you do NOT want to read it from the file system. You should be reading it in through a url resource stream. You can do so by using YourClass.class.getResourceAsStream("/path/to/file")
which will return an InputStream
. So you can do something like
InputStream is = YourClass.class.getResourceAsStream("/path/to/file");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The reason you want to do it this way is that once you have the application in a jar, the path you use reading from the file system will no longer be valid, so it must be read via the classpath. With the code above, the /
is important, as it will bring you to the root of the class path, which (in development terms) starts from the src. So if your file is in a src/resources/file.txt
, then you'd use the path "/resources/file.txt"
Upvotes: 3