0

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!");
       }
    }
}
the tao
  • 253
  • 2
  • 6
  • 13

3 Answers3

3

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

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

Just another idea.

Vidya
  • 29,932
  • 7
  • 42
  • 70
  • 2
    This is probably the best solution, as it also allows you to pack up the text file in a JAR and still use it. – DaoWen Oct 13 '13 at 02:02
1

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".

arcy
  • 12,845
  • 12
  • 58
  • 103
0

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.

Community
  • 1
  • 1
DaoWen
  • 32,589
  • 6
  • 74
  • 101