【发布时间】:2017-07-12 22:05:57
【问题描述】:
请我尝试读取两个文件以进行比较,但是按部分进行比较,所以我同时读取两个文件,并且在每个部分之后我都在执行比较代码,但是第二个文件的缓冲读取器会递增每次更改部分时。
这是我正在使用的代码
static public void compare (String filePath1,String filePath2){
PrintStream console=System.out;
BufferedReader in = null;
BufferedReader inN=null;
BufferedReader in2=null;
BufferedReader in2N=null;
String line = "", line2= "";
boolean command=true;
try {
in = new BufferedReader(new FileReader(filePath1));
inN = new BufferedReader(new FileReader(filePath1));
inN.readLine();
File file = new File("C:/Users/Dell/Desktop/command1.txt");
PrintStream printStreamToFile = new PrintStream(file);
in2= new BufferedReader(new FileReader(filePath2));
in2N= new BufferedReader(new FileReader(filePath2));
in2N.readLine();
File file1 = new File("C:/Users/Dell/Desktop/command2.txt");
PrintStream printStreamToFile1 = new PrintStream(file1);
while ((line = in.readLine()) != null ) {
String next=inN.readLine();
System.setOut(console);
System.out.println("print in 1"+line+" my next is:"+next);
System.setOut(printStreamToFile);
System.out.println(line);
if(next != null && next.contains("#")){
command=true;
while ((line2 = in2.readLine()) != null && command == true ) {
String next2=in2N.readLine();
System.setOut(console);
System.out.println("print in 2"+line2+" my next is: "+next2);
System.setOut(printStreamToFile1);
System.out.println(line2);
if(next2 != null && next2.contains("#")){
System.setOut(console);
System.out.println("I m comparing");
List<String> original = fileToLines(file.getPath());
List<String> revised = fileToLines(file1.getPath());
File fileDiff = new File("C:/Users/Dell/Desktop/commandDiff.txt");
PrintStream printStreamToFileDiff = new PrintStream(fileDiff);
System.setOut(printStreamToFileDiff);
// Compute diff. Get the Patch object. Patch is the container for computed deltas.
Patch<String> patch = DiffUtils.diff(original, revised);
for (Delta<String> delta: patch.getDeltas()) {
System.out.println(delta);
}
command=false;
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (in2 != null) {
try {
in2.close();
} catch (IOException e) {
}
}
}
}
每次调用第一个 while 循环并执行 in.readline() 时,读取器 in2 都会跳过一行。
缓冲区是否有任何特殊性或可以创建任何冲突?
【问题讨论】:
-
没有这样的冲突,建议问题出在你的逻辑上,你在某个地方读了两遍。例如,在`inN = new BufferedReader(new FileReader(filePath1));`之后
in2N.readLine();有什么用? -
-
会不会是因为`command=false`?
-
不,我不这么认为为什么缓冲区会受到影响,我做了一些测试,缓冲区 in2 在第一个 while 循环中直接在 in.readline() 之后跳过了一行。
标签: java file while-loop buffer bufferedreader