Java.io.FileNotFoundException in eclipse

the 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 the program that I write for the class (two private attributes are not used yet, I know), but when I try to run it with the force.txt file, I get the following errors:

An 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 can help me figure this out, it will be very appreciated!

+4
source share
4 answers

You used the relative path to the file that is relevant to your project execution.

If you want to do this, just put the file strength.txtin the base directory of your project. For instance:

enter image description here

absolute . , :

:

C:/dev/myproject/strength.txt

Mac/Unix:

/Users/username/dev/strength.txt

( , ).

+9

System.out.println(openFile.getAbsolutePath());

, JVM .

+3

, ,

    System.out.print(System.getProperty("user.dir"));

, .

,

String filePath = System.getProperty("user.dir");

,

    ImageIcon imageIconRefVar = new ImageIcon(filePath + "/imagepathname");

, , ( , , , )

+2

, .

, :

  • "" → " "
  • "" " ".
  • " " "".
  • Click the "Workspace" button and select the project in the pop-up window, then click "OK"; it will bring you something like $(workspace_loc:proj-1).
  • Add "/ bin" to the end; save the configuration.

I need this instead of just placing the files in the root directory of the project when I perform the assignment, and the professor requires a certain hierarchy of files; moreover, it is more portable than the absolute path.

+1
source

Source: https://habr.com/ru/post/1535858/


All Articles