如何从Java中的文本文件中读取特定行?

时间:2013-11-12 17:54:04

标签: java arrays text-files java.util.scanner

我正在使用文件中的信息创建一个问答游戏。文本文件将包含所有问题,答案和正确答案。文本文件的结构如下:

Question
answer 1
answer 2
answer 3
answer 4
The right answer repeated

使用从文件中读取的信息,我正在创建一个多重测验。我将所有问题保存在一个数组中,另一个数组中的答案,以及不同数组中的正确答案(重复)。有没有办法使用扫描仪,我可以去文件中的某一行?

这是我到目前为止所拥有的。我能够从文件中获取所有问题,但我不知道如何阅读答案(我省略了获取文件名的方法的代码和计算行数的方法因为我知道那些工作):

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

//for the file, it is assumed that it is structured as follows: question /n, answer 1 /n, answer 2 /n, 
//answer 3 /n, answer 4 /n, correct answer repeated

public class CoreCode {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String fileName = getFile();
    // gets the file and deals with exceptions
    Scanner fileIn = null;
    try {
        fileIn = new Scanner(new File(fileName));
    } catch (FileNotFoundException e) {
        System.out.println("Error. File not found.");
        // e.printStackTrace();
    }

    //counts number of lines in the program
    int numberOfLines = countLines(fileIn);

    //Every sixth line is a question
    int numberOfQuestions = numberOfLines / 6;
    fileIn.close();

    fileIn = null;
    try {
        fileIn = new Scanner(new File(fileName));
    } catch (FileNotFoundException e) {
        System.out.println("Error. File not found.");
    }

    //create an array of the questions from the file
    String[] questions = getQuestions(fileIn, numberOfQuestions);
    fileIn.close();
    for (int i = 0; i < questions.length; i++){
        System.out.println(questions[i]);
    }

}

// method to get file name
public static String getFile() {

}

//method to count total lines in file
public static int countLines(Scanner fileIn) {

}

// method to read questions
public static String[] getQuestions(Scanner fileIn, int numberOfQuestions) {
    String[] questions = new String[numberOfQuestions];
    int count = 0;

    //method 2, every sixth line is a question
    while (fileIn.hasNext()){
        String line = fileIn.nextLine();
        if (count == 0 || count % 6 == 0){
            //count is number of total lines, so the index is count  divided by 6 (every sixth lines is 
            //a question
            int index = count / 6;
            questions[index] = line;
        }
        count++;
    }

    return questions;
}

}

2 个答案:

答案 0 :(得分:0)

 LineIterator it = IOUtils.lineIterator(
       new BufferedReader(new FileReader("file.txt")));
 for (int lineNumber = 0; it.hasNext(); lineNumber++) {
    String line = (String) it.next();
    if (lineNumber == expectedLineNumber) {
        return line;
    }
 }

由于缓冲区,这会稍微提高效率。

查看Scanner.skip(..)

答案 1 :(得分:0)

我将BufferedReader的文件作为suggested in another answer读取,并将信息保存在包含以下内容的对象中:

class Question {
    String question;
    String[] answers;
    String correctAnswer;
}

然后,在您阅读完文件后,您将在内存中存储所有问题和答案(存储在ArrayList中)。这样你只会读一次文件。