0

在我的程序的一部分中,我正在读取包含"ua, "并将它们设置为等于我想要处理的行数的行。我想使用数组来使这个灵活到我想要的多行。

这就是它如何使用 4 行

而不是有多个 else if 语句,我想简化它,以便我可以定义一些我想要处理的行,而不必编辑这部分

try (BufferedReader br = new BufferedReader(new FileReader(f.getAbsolutePath()))) {

    String line1 = null, line2 = null, line3 = null, line4 = null, line = null;
    boolean firstLineMet = false;
    boolean secondLineMet = false;
    boolean thirdLineMet = false;

    while ((line = br.readLine()) != null) {
        if (line.contains("ua, ")) {

            if (!firstLineMet) {
                line1 = line;
                firstLineMet = true;
            } else if (!secondLineMet) {
                line2 = line;
                secondLineMet = true;
            } else if (!thirdLineMet) {
                line3 = line;
                thirdLineMet = true;
            } else {
                line4 = line;
                ProcessLines(uaCount, line1, line2, line3, line4);
                line1 = line2;
                line2 = line3;
                line3 = line4;
            }
        }
    }
}
4

2 回答 2

1

或者,您可以执行以下操作以实现您的目标。

int counter = 0;
int limit = 3; // set your limit
String[] lines = new String[limit];
boolean[] lineMet = new boolean[limit];

while ((line = br.readLine()) != null) {
    if (line.contains("ua, ")) {
        lines[counter] = line;
        lineMet[counter] = true; // doesn't make any sense, however
        counter++;
    }
    if (counter == limit){
    // tweak counter otherwise previous if will replace those lines with new ones
        counter = 0; 
        ProcessLines(uaCount, lines); // send whole array 
        lines[0] = lines[1]; // replace first line with second line
        lines[1] = lines[2]; // replace second line with third line
        lines[2] = lines[3]; // replace third line with fourth line

        // ProcessLines(uaCount, lines[0], lines[1], lines[2], lines[3]);
        // Do Something
    }
}

我希望这能帮到您。

于 2013-04-02T18:56:22.753 回答
0

假设读取内存中的整个文件是可以的,您可以使用以下提供的便捷方法Files

List<String> lines = Files.readAllLines(yourFile, charset);
ProcessLines(uaCount, lines.get(0), lines.get(1), ...);

或者,如果您想按顺序处理这些行,但仅限于某个限制:

for (int i = 0; i < limit && i < lines.length(); i++) {
    processLine(lines.get(i));
}
于 2013-04-02T18:11:24.460 回答