April 17, 2009
import java.io.File;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
/**
*
* @author shyam
*/
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception{
String filePath1="c:/file1.txt";
String filePath2="c:/file2.txt";
Test test=new Test();
//Using FileInputStream
if(test.compareFiles(filePath1,filePath2)){
System.out.println("Both the files are same.");
}
else{
System.out.println("Files are not same.");
}
//Using BufferedInputStream on FileInputStream
if(test.compareFilesWithBuffer(filePath1,filePath2)){
System.out.println("Both the files are same.");
}
else{
System.out.println("Files are not same.");
}
}
// A BufferedInputStream adds functionality to another input stream-namely,
// the ability to buffer the input and to support the mark and reset methods.
// When the BufferedInputStream is created, an internal buffer array is created.
// As bytes from the stream are read or skipped, the internal buffer is refilled
// as necessary from the contained input stream, many bytes at a time.
// The mark operation remembers a point in the input stream and the reset
// operation causes all the bytes read since the most recent mark operation
// to be reread before new bytes are taken from the contained input stream.
boolean compareFilesWithBuffer(String filePath1,String filePath2){
try{
File f1 = new File(filePath1);
File f2 = new File(filePath2);
if(f1.length() == f2.length()){
BufferedInputStream bis1=new BufferedInputStream(new FileInputStream(f1));
BufferedInputStream bis2=new BufferedInputStream(new FileInputStream(f2));
while(true){
int a = bis1.read();
int b = bis2.read();
if(a != b){
return false;
}
if(a == -1){
return true;
}
}
}else{
return false;
}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
boolean compareFiles(String filePath1,String filePath2){
try{
File f1 = new File(filePath1);
File f2 = new File(filePath2);
if(f1.length() == f2.length()){
FileInputStream fis1 = new FileInputStream(f1);
FileInputStream fis2 = new FileInputStream(f2);
while(true){
int a = fis1.read();
int b = fis2.read();
if(a != b){
return false;
}
if(a == -1){
return true;
}
}
}else{
return false;
}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
}
Is there a way to vote stuff down here?
[Reply]
Link | April 19th, 2009 at 9:36 PM
if I have more than one statement on a line in file 1, and one statement per line in file2
For example, in File1
System.out.println(”Hello World”); System.out.println(”Hello World again”);
in File2
System.out.println(”Hello World”);
System.out.println(”Hello World again”);
Clearly, the code in both files is the same, but if I use your method of comparing line by line, I presume it won’t work?
[Reply]
Link | January 11th, 2012 at 4:22 PM