简体   繁体   English

在Eclipse(Java)中无法使用Scanner读取txt文件

[英]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). 对于在Eclipse (jre1.8.0_181)中正在处理的项目,我很难读取.txt文件(words.txt)。 I have a copy of words.txt in 我有一个word.txt的副本

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 : 但是,当我尝试建立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. 我在所有尝试中都得到FileNotFoundException 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; ). 我相信我也有正确的导入( import java.io.File;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();
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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