java - 扫描仪正在跳过文本文件行
问题描述
我是 java 新手,遇到这个问题需要帮助。此类从文本文件中读取数据并将其添加到数组 Movie 中。问题是当它读取文本文件时,它会跳过每一行。
public class ReadFile{
private File f;
Scanner sc;
int index;
public ReadFile(){
f = new File("db.txt");
try {
sc = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("An Error occured, File couldn't be opened.");
}
}
public int FileRead(Movie[] film, int index){
sc.useDelimiter(",");
this.index = index;
while(sc.hasNext()){
film[index] = new Movie();
film[index].setTitle(sc.next());
film[index].setYear(sc.next());
film[index].setRuntime(sc.next());
film[index].setActorOne(sc.next());
film[index].setActorTwo(sc.next());
film[index].setDirector(sc.next());
if(sc.hasNextLine()){
sc.nextLine();
}
index++;
}
System.out.println("count is "+ index);
sc.close();
return index;
}
}
解决方案
nextLine()
实际上并没有做你认为它做的事情。
此外,也没有.useDelimiter(",")
- 大概,你的文件是这样的:
Jurassic Park,1993,128,Jeff Goldblum,Jeff Goldblum's looks,Steven Spielberg
The Fly,1986,96,Jeff Goldblum,A fly,David Cronenberg
问题是,计算机就像计算机一样。您说标记之间的分隔符是逗号。没有别的了。所以,这整个事情是一个单一的令牌:
Steven Spielberg
The Fly
如,"Steven Spielberg\nThe Fly"
是您的sc.next()
电话为该行中的第一部电影返回的内容setDirector
。看起来很傻?好吧,你告诉计算机:标记是用逗号分隔的东西。整个内容都被逗号包围,所以,你要了,你明白了:这就是next()
文件中的标记。然后你做了一个其他无用的 nextLine 调用,它吃掉了该行的其余部分The Fly
,因此,不仅导致跳过所有其他电影,而且在下一行(否则跳过)上有一个目录和电影名称的错位组合,错位在一起。你知道,像苍蝇?得到它?[自我提醒:这是一部 1987 年的电影,不,他们不会看的!]
修复可能是告诉扫描仪逗号或换行符算作分隔符;.useDelimiter(",|\r?\n")
会这样做。忘记hasNextLine
+nextLine
部分,它什么都不做,你应该摆脱它。如果那里有一个“断”行(不包含精确 5 个逗号的行),那么您的代码将失败,并且 nextLine 的东西不会解决这个问题,因此,摆脱它。
或者,忘记扫描仪 - 使用 eg 逐行读取Files.readAllLines
,然后逐行处理,使用.split(",")
将其分成几部分。
推荐阅读
- php - php 和 mysql 多个和/或在 select 语句中
- node.js - 如何使用 Node 服务器处理预检 CORS 请求?
- python - 带有代理的python“请求”包不起作用
- android - 2 回收适配器中的视图支架
- c - 具有自动存储持续时间的变量的地址可以在其定义中使用吗?
- javascript - angular 6/rxjs of/map 等中的导入不正确
- ios - map 方法如何在字符串类型上工作?
- python - Python - 不以点开头或结尾的正则表达式 Ip
- javascript - Highchart.js 在纯 IE8 中无法正常工作
- reactjs - 在redux中管理具有ID的多个列表项的状态