简体   繁体   中英

Can't read txt file with Scanner in Eclipse (Java)

I'm having difficulty reading a .txt file (words.txt) for a project I'm working on within Eclipse (jre1.8.0_181). I have a copy of words.txt in

String wordsPath = "C:\\Users\\Administrator\\Documents\\words.txt";

as well as in the project directory itself (which I tried to define multiple ways):

String workingDir = System.getProperty("user.dir");
String wordsPath2 = workingDir.concat("\\words.txt");
String wordsPath3 = new File("").getAbsolutePath().concat("\\words.txt");

However, when I attempt to establish filein :

Scanner filein = new Scanner(new File(wordsPath));
filein = new Scanner(new File(wordsPath2));
filein = new Scanner(new File(wordsPath3));

I get a FileNotFoundException on all attempts. Does anybody have any insight into this? I know the files are there; what else am I missing? I have the right imports as well, I believe ( import java.io.File; and import java.util.Scanner; ). I looked through as many similar questions I could find, no luck. Many thanks!

Both files in below program can be read without any error. Compare and see whether you are doing something wrong.

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

public class ReadFile
{
  public static void main(String[] args)
  {
    try
    {
      Scanner scanner = new Scanner(new File("words.txt"));
      System.out.println(scanner.nextLine());
      System.out.println(scanner.nextLine());

      Scanner scanner2 = new Scanner(new File("C:\\Users\\prasad.karunagoda\\words2.txt"));
      System.out.println(scanner2.nextLine());
      System.out.println(scanner2.nextLine());
    }
    catch (FileNotFoundException ex)
    {
      ex.printStackTrace();
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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