【问题标题】:Reading text file in java using scanner使用扫描仪在java中读取文本文件
【发布时间】:2015-06-08 15:55:39
【问题描述】:

我是初学者。使用扫描仪从 Java 中的文本文件中读取。仅用于读取前 3 个令牌的代码不起作用:

try{
Scanner scFile = new Scanner (new File ("readhere.txt")).useDelimiter("#");
String first = scFile.next();
String second = scFile.next();
int third = scFile.nextInt(); // error here. Why cant I store the integer?
}
catch(FileNotFoundException e){
    System.out.println("Error");
}

我正在尝试仅读取前 3 个标记:

Andrew#Smith#21
John#Morris#55

读取时出现问题 21. java.util.InputMismatchException

【问题讨论】:

  • 您是否尝试检查Scanner 读取的值的类型?如果不是 int,你能看出它是什么吗?
  • 我尝试将下一个标记读取为 scFile.next() 并将其存储为字符串。扫描仪移到下一行并打印:21 John

标签: java file text java.util.scanner


【解决方案1】:

扫描仪将回车字符作为下一个可读标记的一部分包含在内,这会产生无效的整数。你可以这样做

Scanner scanner = new Scanner(new File("readhere.txt")).useDelimiter("#|\r\n");

【讨论】:

  • 这行得通,但仍然需要学习。还有其他解决方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
相关资源
最近更新 更多