Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

java.io.FileNotFoundException in eclipse

Code:

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

public class Driver {

    private int colorStrength;
    private String color;

    public static void main(String[] args) throws IOException {

        String line, file = "strength.txt";

        File openFile = new File(file);
        Scanner inFile = new Scanner(openFile);

        while (inFile.hasNext()) {
            line = inFile.nextLine();
            System.out.println(line);
        }

        inFile.close();
    }
}

This is a small part of a program I am writing for a class (the two private attributes have yet to be used I know) but when I try to run this with the strength.txt file I receive the following errors:

Exception:

Exception in thread "main" java.io.FileNotFoundException: strength.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Driver.main(Driver.java:14)

If anyone with Eclipse could help me figure this out it would be much appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You've used a relative file path which is relative to your project execution.

If you'd like to do it that way, simply put the strength.txt file in the base directory of your project. Like so:

enter image description here

Alternatively, you could reference the absolute file path on your system. For example, use:

Windows:

C:/dev/myproject/strength.txt

Mac/Unix:

/Users/username/dev/strength.txt

(or whatever the full path may be) instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...