无法比较两个文件。 while 循环不起作用
编辑:
我必须文件 FileOne 和 FileTwo,其中每一行都有一个或多个单词。我想比较这两个文件,看看 fileOne 的每一行是否完全相同或 FileTwo 的一行的一部分。我根据你的想法编写了下面的代码,但我的结果太小,这意味着它没有检查 fileOne 的所有行。下面的代码,不是去it1的下一个对象吗?
int index1 = 0;
int index2 = 0;
ArrayList <String> File1 = File2List(FileOne);
Iterator it1 = File1.listIterator();
ArrayList <String> File2 = File2List(FileTwo);
Iterator it2 = File2.listIterator();
while (it1.hasNext()) {
String outer = it1.next().toString();
while (it2.hasNext()) {
String inner = it2.next().toString();
index1 = outer.indexOf(inner);
if(index1 != -1) { //Or compareIgnoreCase
index2++;
it1.next();
break;
}
}
it1.next();
}
System.out.println("Result: "+ index2);
EDIT:
i have to files, FileOne and FileTwo, which in every line there is a word or more. and i want to compare these two file, and see if every line of fileOne is exact the same or piece of a line of FileTwo. I made the code below with your ideas, but i my result is to small that means that it is not ckecking all the lines of fileOne. The code below, isn't going to the next object of it1?
int index1 = 0;
int index2 = 0;
ArrayList <String> File1 = File2List(FileOne);
Iterator it1 = File1.listIterator();
ArrayList <String> File2 = File2List(FileTwo);
Iterator it2 = File2.listIterator();
while (it1.hasNext()) {
String outer = it1.next().toString();
while (it2.hasNext()) {
String inner = it2.next().toString();
index1 = outer.indexOf(inner);
if(index1 != -1) { //Or compareIgnoreCase
index2++;
it1.next();
break;
}
}
it1.next();
}
System.out.println("Result: "+ index2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
首先(在提供实际问题的解决方案之前):
因为
行
Same start
和Same start, diff end
肯定不一样。实际问题:
您正在读取 file1 的每一行的 file2 的全部内容。
可能的解决方案
ArrayList File1
中ArrayList File2
代码>.First (before offering the solution to the actual issue):
by
Because the line
Same start
andSame start, diff end
are certainly not the same.Actual issue:
You're reading the whole contents of file2 at each line of file1.
Possible solution
ArrayList File1
ArrayList File2
.ArrayList File1
, and compare using the previously described function toArrayList File2
.这就是你想要的吗?
一些备注:
containsAll
看起来尽可能与您的要求相似。loadLines
辅助方法,代码也变得更简单,因为您不再需要担心在containsAll
方法中关闭文件。Is that what you want?
Some remarks:
containsAll
looks as similar to your requirement as possible.loadLines
helper method the code also becomes simpler, since you don't need to be concerned about closing the files in thecontainsAll
method anymore.文件一中的一行与文件二中的每一行都是一样的。那是行不通的。您必须在第二个循环中从文件一获取下一行。
例子:
You are one line from file one with every line from file two. That does not work. You have to get the next lines from file one in the second loop.
Example:
这个方法就能完成工作。
This method will do the work.
看来您不仅要检查 file1 与 file2 中的所有行,还要确定它们不同的行。
It appears that you not only want to check is all the line sin file1 against file2 but also determine the line where they differ.