使用数组来实现灵活性

时间:2013-04-02 18:06:24

标签: java arrays bufferedreader

在我的程序的一部分中,我正在读取包含"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;
            }
        }
    }
}

2 个答案:

答案 0 :(得分: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
    }
}

我希望这会对你有所帮助。

答案 1 :(得分: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));
}