简体   繁体   中英

java.io.FileNotFoundException question

I have a text file text.txt located in the classes output root directory.

When I use new File("text.txt"), i received the java.io.FileNotFoundException.

My output structure is liking

com
    mycompany
         test.class
text.txt

Anything wrong and how to fix?

When you don't give an absolute location for a file it searches from where you launched the program (your working directory). So, launch your application in the same directory as that file or move the file to where ever you are launching from.

If you want to read a file relative to your classpath however, you need to do something like this...

reader = new BufferedReader(new InputStreamReader(
    getClass().getClassLoader().getResourceAsStream("test.txt")));

It will use the current working directory. From the Java documentation ( http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#File%28java.lang.String%29 ):

By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

new File("text.txt") is relative to your working directory. You could use this.getClass().getResourceAsStream("text.txt") to load a file from the classpath.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM