tags:

views:

95

answers:

3

I've created this simple program in Eclipse:

import java.util.*;
import java.io.*;

public class prob1 {
    public static void main(String[] args)
    {

        try
        {
            FileReader in = new FileReader("practice.in");
            Scanner scanner = new Scanner(in);

            while(scanner.hasNext())
            {
                int number = scanner.nextInt();
                if(number==0)break;
                int sum = 0;

                for (int i=0; i<number; i++)
                {
                    int x = scanner.nextInt();
                    sum += x;                
                }
                System.out.println("Sum = "+sum);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }


    }
}

I also have a "practice.in" file in the same folder as this practice.java file is (the src folder in Eclipse."

However, when I try to run it, it can never find it. What is eclipse doing with the paths that I can simply do FileReader("practice.in") when practice.in is in the same directory as the java file? Does this have something to do with my workings directory?

+3  A: 

The default folder in eclipse is the project root, not the src folder. You need to move the file or specify the relative path of "src/practice.in"

Jherico
A: 

Java would access the file relative to the directory from which the java command is being run, which is your project root directory. So you would have to give the full path to that file, starting at the project root.

Additionally, if you're the Spring library, you can use the application context to find a file with a given name anywhere in the classpath.

Kaleb Brasee
+2  A: 

If practice.in levels at the same directory level as your java file, then you can also use Class.getResourceAsStream():

InputStream steam = prob1.class.getResourceAsStream("practice.in");
Scanner scanner = new Scanner(stream);
...

This would work regardless of where you invoked the java file.

notnoop