java - 无法在 Eclipse (Java) 中使用 Scanner 读取 txt 文件
问题描述
我在Eclipse (jre1.8.0_181) 中正在处理的项目中读取.txt文件 (words.txt)时遇到困难。我有一个words.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();
}
}
}
推荐阅读
- php - 调用构造函数时未初始化静态属性php
- algorithm - Insert N numbers in a maximum binary heap
- javascript - how to delete eventListener. removeEventListener doesn't work
- python - How can I properly run 2 threads that await things at the same time?
- javascript - How to block/break/disable a request from a third-party tool?
- format - Excel VBA:在下面创建新行并仅复制带有公式的单元格
- javascript - Can you use JavaScript for changing a existing Python variable?
- c# - 发布 Visual Studio 应用程序时 SoundPlayer 不工作
- notepad++ - 如何使用记事本++复制一段XML文件并创建一个新文件
- javascript - 使用动态键对数组进行排序