基本上,我正在尝试设置一个从文件读取数据的扫描仪。我知道文件名是什么,但我不知道它在哪里。出于测试目的,我可能知道,但如果我的老师测试了它,我就不知道文件在他们设备上的位置了。
奇怪的是,我甚至不能让它在知道目录的情况下工作。根据我所搜索的,人们说当你仅仅使用:"testdata.txt“搜索一个文件时,它应该搜索你的项目所在的当前目录。我尝试过将我的测试文件放到项目所在的文件夹中,但仍然得到了一个FileNotFoundException。
// Make scanner and read jobs into array
String fileName = "testdata.txt";
Scanner sc = new Scanner(new File(fileName));
发布于 2019-06-10 05:20:09
我建议使用FileInputStream
类和BufferedReader
类。根据我的经验,Scanner
类有点奇怪。如果您仅从文件中读取,则可以尝试执行以下操作:
File file = new File("path.txt");
List<String> jobs = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(file)) {
String line = "";
while ((line = reader.readLine()) != null) {
jobs.add(line);
}
} catch (IOException e) {
// handle errors
}
String[] jobArr = new String[jobs.size()];
jobs.toArray(jobArr);
这样,您还可以逐行阅读,并分别处理每一行。
https://stackoverflow.com/questions/56518331
复制相似问题