使用Java中的Scanner类从文件中读取

时间:2015-01-21 02:52:00

标签: java file-io

我试图从文件中读取并将输出作为标记传递给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)

请帮助。

1 个答案:

答案 0 :(得分:0)

每次拨打sc.nextLine()时,您都会读到另一行。因此,在循环的第一次迭代中,if(map.containsKey(sc.nextLine()))读取第一行,并检查它是否在地图中。 count += map.get(sc.nextLine())读取第二个行,从地图中获取该值并将其添加到计数中。 map.put(sc.nextLine(), count)读取第三个​​行并将计数存储在那里。如果有三行以上,则循环再次运行,并读取第4/5/6行。

您需要使用变量来存储当前行,因为您只能读取每一行:

        while(sc.hasNextLine()){
            String line = sc.nextLine();
            if (map.containsKey(line)){
                count+= map.get(line);
            }
            map.put(line, count);

        }
相关问题