[英]Reading from a file using a Scanner Class in Java
我正在尝试从文件读取并将输出作为令牌传递给HashMap对象。 似乎我的程序似乎找不到文件。 这是代码。
public static void main(String[] args) {
try {
HashMap<String, Integer> map = sortingFromAFile("file.rtf");
System.out.println(map);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static HashMap sortingFromAFile(String fileName) throws FileNotFoundException {
HashMap<String, Integer> map = new HashMap<String, Integer>();
Integer count = 1;
File file = new File(fileName);
Scanner sc = null;
try {
sc = new Scanner(file);
while(sc.hasNextLine()){
if (map.containsKey(sc.nextLine())){
count+= map.get(sc.nextLine());
}
map.put(sc.nextLine(), count);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return map;
}
我要读取的文件位于项目目录的根目录中。
这是错误。
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at com.soumasish.Main.sortingFromAFile(Main.java:38)
at com.soumasish.Main.main(Main.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
请帮忙。
每次调用sc.nextLine()
都会读取另一行。 因此,在循环的第一次迭代中, if(map.containsKey(sc.nextLine()))
读取第一行,并检查其是否在地图中。 count += map.get(sc.nextLine())
读取第二行,从地图中获取该值并将其添加到count中。 map.put(sc.nextLine(), count)
读取第三行并将计数存储在那里。 如果多于三行,则循环再次运行,并读取第4/5/5 / 6th行。
您需要使用一个变量来存储当前行,因为您只能读取每行一次:
while(sc.hasNextLine()){
String line = sc.nextLine();
if (map.containsKey(line)){
count+= map.get(line);
}
map.put(line, count);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.