[英]Can't read txt file with Scanner in Eclipse (Java)
对于在Eclipse (jre1.8.0_181)中正在处理的项目,我很难读取.txt文件(words.txt)。 我有一个word.txt的副本
String wordsPath = "C:\\Users\\Administrator\\Documents\\words.txt";
以及项目目录本身(我尝试定义多种方式):
String workingDir = System.getProperty("user.dir");
String wordsPath2 = workingDir.concat("\\words.txt");
String wordsPath3 = new File("").getAbsolutePath().concat("\\words.txt");
但是,当我尝试建立filein
:
Scanner filein = new Scanner(new File(wordsPath));
filein = new Scanner(new File(wordsPath2));
filein = new Scanner(new File(wordsPath3));
我在所有尝试中都得到FileNotFoundException
。 有人对此有见识吗? 我知道文件在那里。 我还想念什么? 我相信我也有正确的导入( import java.io.File;
和import java.util.Scanner;
)。 我浏览了许多类似的问题,没有运气。 非常感谢!
可以正确读取以下程序中的两个文件。 比较并查看您是否做错了什么。
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.