please help me to make the code

package utils;

import java.io.*;

class compare { public static void main(String args[]) throws IOException {

 FileInputStream file1 = new InputStream(args[0]);
 FileInputStream file2 = new InputStream(args[1]);

 try {
 if(args.length != 2)
  throw (new RuntimeException("Usage : java compare <filetoread> <filetoread>"));

                while (true) {
                   int a = file1.read();
                   int b = file2.read();
                   if (a==-1) { 
                   System.out.println("Files match"); 
                   System.out.println("Files do not match");

 catch (IOException ioe) {
  System.out.println("Error: " + ioe);
 catch (Exception e) {
  System.out.println("Error: " + e);



+2  A: 

The simplest way is to read the contents into two strings e.g.

  FileInputStream fin =  new FileInputStream(args[i]);
  BufferedReader myInput = new BufferedReader
              (new InputStreamReader(fin));
  StringBuilder sb = new StringBuilder();
  while ((thisLine = myInput.readLine()) != null) {  

, and perform a .equals() on these. Do you require more complex differencing capabilities ?

Brian Agnew
no, the simpler the better.can u tell me how to implement it?
Stefannus Temaatmadja
I'm not the answer isn't pretty much in the above
Brian Agnew
yeah! it works!! thanks!
Stefannus Temaatmadja
If the files are too big, you could always read them in fixed-size chunks and compare a chunk at a time. Actually this would be a more efficient solution even if the files aren't big enough to blow memory, as once you find one character different, they must be different, and there's no point reading more.
Also, if the files are or could be binary, you probably should read them into a byte array rather than a String.
The question says "2 text files"
Brian Agnew

Read the contents of the files and use the MessageDigest class to create an MD5 hash of the contents of each file. Then compare the two hashes. This has the advantage of working for binary files as well.

Eric Petroelje
True, but isn't definitive. Two files could hash to the same value but be different. I suppose an MD5 hash is big enough and unpredictable enough that this is unlikely, but I'm always nervous of algorithms that work "most of the time".
A much bigger problem is that this method is fairly inefficient -- it always reads the entirety of both files, even if (for example) there's a difference in the first byte. Comparing blocks directly gives an 'early out', so you quit comparing as soon as you find a difference. Hashing is more useful if you're doing something like finding any duplicates across a file system, so you want to compare file X against tens of thousands of others. In this case, if you get a duplicate hash, you can compare the files themselves to verify that they're really the same.
Jerry Coffin