the tao
the tao

Reputation: 341

Why isn't java finding my file

Trying to learn how to read text files in Java. I have placed the text file within the same folder as IdealWeight.java. Am I missing something here?

IdealWeight.java

package idealweight;

import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class IdealWeight 
{
    public static void main(String[] args) 
    {
       Scanner fileIn = null; //Initializes fileIn to empty
       try 
       {
           fileIn = new Scanner
                   (
                        new FileInputStream
                            ("Weights.txt") 
                   );
       }
       catch (FileNotFoundException e)
       {
           System.out.println("File not found!");
       }
    }
}

Upvotes: 0

Views: 160

Answers (3)

Vidya
Vidya

Reputation: 30310

You could also put the file in the classpath and then do this:

InputStream in = this.getClass().getClassLoader()
                                .getResourceAsStream("Weights.txt");

Just another idea.

Upvotes: 3

DaoWen
DaoWen

Reputation: 33029

You need to put Weights.txt in your working directory, not in the directory with the source file. If you're using Eclipse or a similar IDE, the this is probably the project root. As per this answer, you can use this snippet to get the full path to your working directory:

System.out.println("Working Directory = " + System.getProperty("user.dir"));

Check the result of running that command, and that should tell you where to put your text file. Once you have the text file in the right place then the code you posted should work fine.

Upvotes: 0

arcy
arcy

Reputation: 13153

The java file IO system does not look for the file in the same directory as the class, but in the "default" directory for the application. Any application you run has a directory that it regards as its default, and that's where it would attempt to open this file. Try putting a full pathname to the file.

Or put the file you want to read in a directory, and run the application from that directory (in a terminal window) with "java IdealWeight".

Upvotes: 1

Related Questions