【问题标题】:Read first 5 lines from file and then the rest从文件中读取前 5 行,然后读取其余行
【发布时间】:2013-04-26 16:59:26
【问题描述】:

免责声明:这是作业,所以我的工作受到一些限制。

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

文件如下所示:

Name  
Label1  
Label2  
Button1  
Button2  
Button3  
word0,word0  
word1,word1  
etc  

我已经能够使用以下代码读取 (word0,word0 等) 中的单词对(前 5 行是加法,因此现在可能无法使用):

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 行,然后返回一个对象,就像上面的代码对 wordpairs 所做的那样,但我无法得到任何工作。然后我想我需要让现有代码跳过开头。

如您所见,我在这里很困惑,所以如果有人能指出我正确的方向,我将不胜感激!

【问题讨论】:

  • 您可以对其进行硬编码 - 只需将 5 个变量分配给调用 scanner.next 5 次的输出。由于格式有点硬编码,这可能是最简单的方法。

标签: java io java-io


【解决方案1】:

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

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】:

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

    int c = 0;
    while (scan.hasNext()) {
        if (c < 5){
            //do something
            //first 5 lines
        }
        else{
            //otherwise
            //next lines
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 2015-04-11
      • 1970-01-01
      相关资源
      最近更新 更多