简体   繁体   English

用Java比较具有特定结构的文件

[英]Comparing files with a specific structure in java

I have two txt files with a specific structure. 我有两个具有特定结构的txt文件。 There should be som empty rows and rows with some data. 应该有一些空白行和一些数据行。 Something like this: 像这样:

@RELATION Table

@RECORD 1
ID '5'
SOMETHING '10'

The point is, there can be 10 'empty' rows in one file and there can none in second and if the data equals, it should not matter. 关键是,一个文件中可以有10个“空”行,而第二个文件中可以没有空行,如果数据相等,那就没关系了。 Any ideas how to effectively do it with big files ? 有什么想法可以有效地处理大文件吗?

BufferedReader should be used to read from file, supplying a FileReader to its constructor: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html 应该使用BufferedReader读取文件,并为其构造函数提供FileReader: https : //docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html

So you will have two of them, one for each file. 因此,您将拥有两个,每个文件一个。

Have an "infinite loop" such as: while(true){} 有一个“无限循环”,例如:while(true){}

Within this container loop, you should have two internal loops, one for each file. 在此容器循环中,您应该有两个内部循环,每个文件一个。

In each internal loop, using the method readLine() you should advance the cursor to the next line. 在每个内部循环中,应使用readLine()方法将光标移至下一行。

declare this outside of the container loop: 在容器循环之外声明:

String lineFromFileA, lineFromFileB;

and then: 接着:

while((lineFromFileA = bufferedReaderA.readLine()) != null){
    if(!lineFromFileA.isEmpty())
        break;
}

do the same with lineFromLineB. 对lineFromLineB进行相同操作。

an alternative to the above loop is: 上述循环的替代方法是:

while((lineFromFileA = bufferedReaderA.readLine()) != null && lineFromFileA.isEmpty());

After the two internal loops, both lineFromFileA and lineFromFileB are either null or has a value that is not an empty String. 在两个内部循环之后,lineFromFileA和lineFromFileB均为null或具有非空String的值。

If both are null, then you are done with the comparison, the two files are equal and you may return true from the function. 如果两者都为null,则比较完成,两个文件相等,并且可以从函数返回true。

If one contains null and the other does not, return false. 如果一个包含null,而另一个不包含null,则返回false。 The files are different. 文件是不同的。

If both are not null, then check the equals() method if the two Strings are identical, if they are not, return false from the function. 如果两个都不为null,则检查equals()方法是否两个String相同,如果不相同,则从函数返回false。 If they are equal, do nothing, the next iteration of the container loop will handle the next line. 如果它们相等,则不执行任何操作,容器循环的下一次迭代将处理下一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM