开发者

When I try to read a file with Java using Eclipse, it always says it can't find it?

开发者 https://www.devze.com 2022-12-09 09:49 出处:网络
I\'ve created this simple program in Eclipse: import java.util.*; import java.io.*; public class prob1 {

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("pra开发者_如何学编程ctice.in") when practice.in is in the same directory as the java file? Does this have something to do with my workings directory?


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"


If practice.in levels at the same directory level as your java file, then you can also use [Class.getResourceAsStream()](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)):

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

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


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.

0

精彩评论

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

关注公众号