如何重置扫描仪? [英] How to reset Scanner?

查看:143
本文介绍了如何重置扫描仪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个文本文件,并将每一行放入一个String(字符串数组)中.但是,这需要扫描文件两次,一次是找出有多少行,另一次是创建该大小的字符串数组.但它会引发错误,并且reset方法似乎不起作用.

I want to read a text file and put each line in a String (array of Strings). However that requires scanning file twice, one to figure out how many line are there and another time to create an array of strings of that size. but it throws an error and reset method doesn't seem to work.

    FileReader read = null;

    try {
        read = new FileReader("ModulesIn.txt");
        //scan through it and make array of strings - for each line
        Scanner scan = new Scanner(read);
        while(scan.hasNextLine()){
            numOfMods++;
            scan.nextLine();
        }

        scan.reset();

        lines = new String[numOfMods];

        for(int i = 0; i < numOfMods; i++)
            lines[i] = scan.nextLine();

这是相关代码的片段.

推荐答案

使用标准数组跳过...浪费时间扫描文件,然后再次扫描.而是使用具有动态大小的arraylist,然后将其转换为标准数组.

Skip using a standard array... it's a waste of time to scan through the file and then scan through again. Use an arraylist instead which has a dynamic size and then convert it to a standard array afterwards.

 BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
        String str;

        List<String> list = new ArrayList<String>();
        while((str = in.readLine()) != null){
            list.add(str);
        }

        String[] stringArr = list.toArray(new String[0]);

这篇关于如何重置扫描仪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆