No such file or directory found even though the file is in the same package

3.5k views Asked by At

I am trying to scan the "loremIpsum.txt" file to a String using the split method of the class String to store each word in a different position of an array, and last use a HashSet to find if there is any word repetition in the text.

But Eclipse doesn't recognize the file even though it is in the same package. I was wondering if there is something wrong with my code?

package Lab5;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;

public class Lorem {

    public static void main(String[] args) {
        String[] loremIpsum = null;
        try {
            loremIpsum = new Scanner(new File("loremIpsum.txt")).next().split(" ");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        System.out.println(loremIpsum.length);
        HashSet h = new HashSet();

        for(int i=0;i<loremIpsum.length;i++) {
            String word=loremIpsum[i];
            System.out.println(word);
            if(h.contains(word)) {
                System.out.println("we found a duplicate");
            } else {
                h.add(word);
            }   
        }

    }

}

Error message and proof "lorem.txt" is in the same package:
error message and proof "lorem.txt" is in the same package

3

There are 3 answers

0
Ouroboros On

The file will be looked for in the project directory (where bin and src folders are located). Move the file there.

0
Andy Thomas On

When you call the File constructor with a relative path, it's relative to the working directory.

That usually won't be the same directory as the code calling the constructor. But that's okay, because if your file can be specified when you run the application, you don't want to presume that anyway.

You can specify the working directory in the Eclipse run configuration, on the Arguments tab.

You can see how a relative path has been resolved using the File method getAbsolutePath().

   try {
        File myFile = new File("loremIpsum.txt");
        System.out.println("Absolute path = " + myFile.getAbsolutePath() );

        loremIpsum = new Scanner(myFile).next().split(" ");
        ...
1
Jay On

You need to pass the parameter as a path.

try this

String path = new File("").getAbsolutePath();

path.concat("/loremIpsum.txt");

loremIpsum = new Scanner(new File(path)).next().split(" ");

basically youre just finding the current path and appending the file name youre wanting to read from. Like the others said though, you can move it to your working directory as well.

Cheers!