-2

I'm trying to read in a file, and throw each word into an arraylist, but it keeps saying it can't find the file. I've double checked (and triple, and quadruple, lol) that the file names match with correct extension and in the same directory. I feel like I'm missing something obvious. Also, I know there are other ways to read a file, but we haven't learned those yet in my class so I want to get this to work using the Scanner class.

public class FrequencyAnalysis {
    private static ArrayList<String> words = new ArrayList<>();

    public static void read() throws IOException {
        String token;
        Scanner inFile = new Scanner(new File("plaintext.txt"));

        while (inFile.hasNext()){
            token = inFile.next();
            words.add(token);
        }
    }
}

public class FrequencyAnalysisTester  {
    public static void main(String[] Args) throws IOException {

        FrequencyAnalysis.read();
    }
}
Jenelle
  • 3
  • 1
  • So `FrequencyAnalysis.java`, `FrequencyAnalysisTester.java` and `plaintext.txt` are all sitting right next to each other in a directory, and from that directory you run `javac FrequencyAnalysisTester.java` and `java FrequencyAnalysisTester`? – Andreas Jun 23 '18 at 06:37
  • 3
    Add `System.out.println(new File("."). getAbsolutePath());` to see what the "working" directory actually is (also you can use `System.getProperty("user.dir")`) – MadProgrammer Jun 23 '18 at 06:37
  • @Andreas Yep, already updated ;) – MadProgrammer Jun 23 '18 at 06:40
  • This answer may help you , check https://stackoverflow.com/questions/1480398/java-reading-a-file-from-current-directory – Nidhin Jun 23 '18 at 06:41
  • Where this file located, inside your project, Then you cant access it like you did because when you create a jar it will be inside that generated jar – Keaz Jun 23 '18 at 06:53
  • I just recreated your case by adding imports, placing both public classes into different files, filling the plaintext.txt with some Strings, and adding a for-each loop to iterate thru the ArrayList. Everything works is it should... – Igor Soudakevitch Jun 23 '18 at 07:04

1 Answers1

0

The current directory may differ from the directory of .class file. If your file is in the class path ,this code solve your problem

 URL path = ClassLoader.getSystemResource("myFile.txt");
 File f = new File(path.toURI());

Refer this answer for more details Java, reading a file from current directory?

Nidhin
  • 1,818
  • 22
  • 23