开发者

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.FileNotFou开发者_运维问答ndException.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜