2

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?

3 Answers 3

5

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")));
Sign up to request clarification or add additional context in comments.

3 Comments

I am launching inside the eclipse, but still don't know where to put this file inside if using relative path.
you can give a working directory in your project run properties under the arguments tab. The default is the root project folder.
You are right! Thanks. BTW, how to give the working directory argument, is it project_path?
1

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.

Comments

0

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.

2 Comments

You said in another comment that you're using Eclipse. You can set the working directory in the arguments tab of the launch configuration dialog.
yeah, just want to know which veriable to use to set the working directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.