简体   繁体   English

当我尝试使用Eclipse使用Java读取文件时,总是会显示找不到文件?

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

I've created this simple program in Eclipse: 我已经在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." 我也有一个“ practice.in”文件与此练习.java文件位于同一文件夹中(Eclipse中的src文件夹。”

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? 当Practice.in与Java文件位于同一目录中时,eclipse如何处理我可以简单地执行FileReader(“ practice.in”)的路径? Does this have something to do with my workings directory? 这与我的工作目录有关吗?

The default folder in eclipse is the project root, not the src folder. eclipse中的默认文件夹是项目根目录,而不是src文件夹。 You need to move the file or specify the relative path of "src/practice.in" 您需要移动文件或指定“ 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)) : 如果practice.in级别与Java文件位于同一目录级别,则还可以使用[ 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文件,都可以使用。

Java would access the file relative to the directory from which the java command is being run, which is your project root directory. Java将访问相对于运行Java命令的目录的文件,该目录是您的项目根目录。 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. 另外,如果您是Spring库,则可以使用应用程序上下文在类路径中的任何位置查找具有给定名称的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM