检查 java 中记录的架构

Check schema of a record in java

我有一个文本文件。文件中的每一行代表一个记录,该记录有 'n' 列,由 | 分隔(管道)字符。列值是 int、string、date、timestamp 等类型。空字符串和空格也可以作为列值。

我只验证列值的计数,不需要验证数据类型。

每行 5 列的样本有效记录:

1234|xyz|abc|2016-04-08 11:12:40|234
1235|efgh|abc|2016-04-09 11:25:40|
1236|efghij| ||

验证码:

boolean valid = true;
String line = buffReader.readLine();
String[] tokens = null;
while (line != null){
    tokens = line.split("\|");
    if ((tokens.length==4 || tokens.length==5) && countPipes(line)==4){

    } else {
        valid = false;
        break;
    }
    line = buffReader.readLine();
}

private int countPipes(String line){
    int count = 0;
    count = line.length() - line.replace("|", "").length();
    return count;
}

感觉代码还可以更好。 有人可以告诉我如何改进这段代码吗?

首先也是最重要的一点:您的 if 语句中出现严重错误,因为您使用的是单个 =(赋值运算符)而不是比较运算符 ==!!

关于代码清理:这只是一个轻微的调整,可能有更好的方法来验证这一点,但这是我想到的第一件事:

boolean valid = true;
String line = buffReader.readLine();
while (valid && (line != null)){
    String[] tokens = line.split("\|");
    valid = !(tokens.length == 4 || tokens.length == 5);
    line = buffReader.readLine();
}

好吧,您可以简单地检查线路中是否有四个管道。如果恰好有四个管道,则有五列,可能为空(您允许)。

while (line != null) {
    if ( countPipes(line) != 4 ) {
        valid = false;
        break;
    }
    line = buffReader.readLine();
}

现在你根本不需要拆分线。

关于拆分的注意事项。如果使用带有两个参数的 split 并使用负数,则拆分也将包含空元素的条目。这是一个演示:

public class Test {

    public static void main(String[] args) throws IOException {
        String line = "A|B|||";

        String[] zeroSplit = line.split("\|");
        String[] negativeSplit = line.split("\|",-1);

        System.out.println( "When split without parameter: " + zeroSplit.length );
        System.out.println( "When split with negative parameter: " + negativeSplit.length );
    }
}

这里的输出是:

When split without parameter: 2
When split with negative parameter: 5

因此在这种情况下,您可以检查拆分的长度是否恰好为 5,并获得相同的结果。

while (line != null) {
    if ( line.split("\|",-1).length != 5 ) {
        valid = false;
        break;
    }
    line = buffReader.readLine();
}