首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从文件中读取前5行,然后读取其余行

从文件中读取前5行,然后读取其余行
EN

Stack Overflow用户
提问于 2013-04-27 00:59:27
回答 2查看 2K关注 0票数 1

免责声明:这是作业,所以我在一些限制下工作。

我需要读取文件的前5行,并使用这些字符串来更改标签和按钮,然后将文件的其余部分保存为数组列表。

该文件如下所示:

代码语言:javascript
复制
Name  
Label1  
Label2  
Button1  
Button2  
Button3  
word0,word0  
word1,word1  
etc  

我已经能够用下面的代码读取( word0,word0等)中的单词对(前5行是加法,所以它现在可能不起作用):

代码语言:javascript
复制
public static ArrayList loadFile(String filename) {
    ArrayList<Wordpair> temp = new ArrayList<>();
    try {
        FileInputStream fis;
        fis = new FileInputStream(filename);
        //Scanner to read individual lines from a file
        Scanner scan = new Scanner(fis);
        while (scan.hasNext()) {
            String line = scan.nextLine();
            //Scanner to read individual items from a string 
            Scanner lineScan = new Scanner(line);
            lineScan.useDelimiter(",");
            String question = lineScan.next();
            String answer = lineScan.next();
            //Create the new Wordpair
            Wordpair wp = new Wordpair(question, answer);
            //Add the new wordpair to the list
            temp.add(wp);
        }
        scan.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(IO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return temp;
}

我的想法是将文件的前5行保存为一个单独的对象,该对象只包含在文件中找到的信息,但我不知道如何做到这一点。我最初的想法是创建一个新的方法,它只读入前5行,然后返回一个对象,就像上面的代码对单词对所做的那样,但我一直无法让任何东西正常工作。然后我想我需要让现有的代码跳过开头。

正如你所看到的,我在这里很困惑,所以如果有人能给我指引正确的方向,我将非常感激!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-04-27 01:04:56

我会在你的while循环中使用一个计数器。

代码语言:javascript
复制
int count = 0;
while (scan.hasNext()) {
        String line = scan.nextLine();
        //Scanner to read individual items from a string 
        Scanner lineScan = new Scanner(line);
        lineScan.useDelimiter(",");
        String question = lineScan.next();
        String answer = lineScan.next();

        if (count < 5)
          //lineScan contains one of the first 5 lines
          //call a method to do something with these lines here
        else {
          //Create the new Wordpair
          Wordpair wp = new Wordpair(question, answer);
          //Add the new wordpair to the list
          temp.add(wp);
        }

        count++;
    }
票数 2
EN

Stack Overflow用户

发布于 2013-04-27 01:09:26

你可以在你的循环中使用计数器:

代码语言:javascript
复制
int c = 0;
while (scan.hasNext()) {
    if (c < 5){
        //do something
        //first 5 lines
    }
    else{
        //otherwise
        //next lines
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16241597

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档