How to RELIABLY compare two File objects?

Hi java community!
I have two File objects and I need to know whether they both point to the same file on the system. First, I tried using the equals() method of the File object, but later I found that this often returns false even when file being pointed to by both objects is the same file.
For example:
  public static void main(String[] args) throws Exception {
    File mFileA = new File("C:\\PROGRA~1\\MYPROG~1\\MYDATA~1.TXT");
    File mFileB = new File("C:\\Program Files\\My Program\\My Data File.txt");
    DataInputStream mInputA = new DataInputStream(new BufferedInputStream(new FileInputStream(mFileA)));
    DataInputStream mInputB = new DataInputStream(new BufferedInputStream(new FileInputStream(mFileB)));
    System.out.println("Contents of file A:");
    while (mInputA.available() > 0) {
      System.out.println(mInputA.readLine());
    System.out.println("\nContents of file B:");
    while (mInputB.available() > 0) {
      System.out.println(mInputB.readLine());
    System.out.println("\nAre file A and file B the same file?");
    System.out.println(mFileA.equals(mFileB) ? "Yes" : "No");
  }Running this gives the following output:
Contents of file A:
First line of the file.
Second line of the file.
Third and final line of the file.
Contents of file B:
First line of the file.
Second line of the file.
Third and final line of the file.
Are file A and file B the same file?
NoIt seems that the different representation of the paths (short 8.3 file names, vs. long file names) is confusing Java into believing that they are two separate files, even though the example above confirms that they are in fact the same file by showing the contents from input streams derived by the two File objects (which are, needless to say, identical).
So, does anyone know how to reliably determine whether two File objects point to the same file?
Cheers,
Martin

sabre150 wrote:
Bren_McGuire wrote:
Thanks guys.
I'd just found it too right after I made this post. :p95% of the time the promised Dukes never arrive so thanks for the Dukes.Ditto

Similar Messages

  • How to compare two files in java & uncommon text should print in text file.

    Hi,
    Can any one help me to write Core java program for this.
    How to compare two files in java & uncommon text should print in other text file.
    thanks
    Sam

    Hi All,
    i m comparing two HTML file.. thats why i am getting problem..
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class textmatch{
    public static void main(String[] argv)
    throws Exception{
    BufferedReader fh =new BufferedReader(new FileReader("internal.html"),1024);
    BufferedReader sh = new BufferedReader(new FileReader("external.html"),1024);
    String s;
    String y;
    while ((s=fh.readLine())!=null)
    if ( s.equals(y=sh.readLine()) ){    
    System.out.println(s + " " + y); //REMOVE THIS PRINTLN STATEMENT IF YOU JUST WANT TO SHOW THE SIMILARITIES
    sh.close();
    fh.close(); }
    thanks
    Sam

  • How to compare two files in Java & uncommon text should print in Diff text

    Hi All,
    can any one help me to write a java program..
    How to compare two files in Java & uncommon text should print in Diff text file..
    Thanks
    Sam

    Hi All,
    i m comparing two HTML file.. thats why i am getting problem..
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class textmatch{
    public static void main(String[] argv)
    throws Exception{
    BufferedReader fh =new BufferedReader(new FileReader("internal.html"),1024);
    BufferedReader sh = new BufferedReader(new FileReader("external.html"),1024);
    String s;
    String y;
    while ((s=fh.readLine())!=null)
    if ( s.equals(y=sh.readLine()) ){    
    System.out.println(s + " " + y); //REMOVE THIS PRINTLN STATEMENT IF YOU JUST WANT TO SHOW THE SIMILARITIES
    sh.close();
    fh.close(); }
    thanks
    Sam

  • How to compare two files char by char

    Hi,
    I want to compare two files and after Comparison i want all the differences in the new file has to be updated to old file (Without deleteing the contents of the file)?
    Any help will be appriciated.
    Thanks.

    I think i have to elaborate my question�.. for
    example take a file called xyz.xml which contain some
    data which I don�t want to get deleted� after some
    days this file has been modified (i.e. some more data
    has been added) . Now without overwriting the file
    /deleting the earlier contents of file xyz.xml. How
    do I update xyz.xml file?
    Now I think iam clear.
    Thanks.This does not make sense at all! Either your file has been changed or it has not. If it has been changed then there is nothing to do. If it has not been changed then there is nothing to do.

  • How to open acrobat in java and compare two files using javacode

    I am absolutely new to use acrobat software in Java. I want to open two pdf files at a time and then compare the differences between them thru java program .
    i am not sure how to do it. iam trying many ways without success.
    I used jre and could open open files using runtime method , but couldn't do comaparision. i..e could't access tools menu (alt+t) Compare two files and <enter>. help in java will be appreciated.
    Pls guide me the steps to use the acrobat library. At http://partners.adobe.com/asn/acrobat i found supporting vb and vc only.
    Any help or links are greatly appreciated.

    iText is an open source PDF library, reads a PDF one page at a time. You could check it out. I've used it for writing/splitting/concatenating PDFs, but not comparing files
    http://www.lowagie.com/iText/
    Scott
    http://www.swiftradius.com

  • How to compare two files using MD5?

    Hi,all:
    How to compare two files to know if they're the same without any difference?I want to use MD5, but I just konw how get a message digest of a string. How to get a message digest of a file? Or there is other method to compare two files?
    Thanks advance!

    This is starting to sound rather a lot like a homework problem.
    An MD5 message digest is simply a 16 byte array. To compare two message digests...
    byte[] md5incoming = ...
    byte[] md5comparison = ...
    if( md5incoming.equals(md5comparison) ) {
       System.out.println("MD5 Checksums match");
    }To find out how to generate an MD5 checksum, please look up MessageDigest in the API documentation, and do a google search for "MD5 java"
    In a networked scenario, there are two issues - firstly the performance in sending copies of files all over the place (imagine if it's a 10Gb file to be compared over a 14.4K modem link, this would take a while). Secondly, the network link itself might insert an error in the file and you'd get a false miss.
    By only sending MD5 digests over the link, you simultaneously reduce the error (shorter files are less likely to be corrupted) and reduce the transmission time (16 bytes takes practically no time to transmit over damp string, let alone any sort of sensible device).
    D.

  • Linux Diff tool as External tool in Jdev to compare two files

    Hi, I was looking for adding any diff tool to compare two files in Jdev. I added the usual Linux "diff <file1> <file2>" to compare two files. The way I have provided arguments compares a file against itself.
    Program: diff
    Arguments: ${file.name} ${file.name}
    Directory: ${file.dir}
    My requirement to to right click on the two files which I want to compare and the open them in any diff tool.
    Any ideas?
    Regards,
    Ramesh

    Which jdev version?
    I don't see how this can be done. How do you select two files in jdev?
    As you provided the same name as file1 and file2 it's clear that you compare the file to itself.
    Timo

  • Compare two Java Objects without Comparable / Comparator

    Hi Friends,
    I would like to compare two java objects (lots o attributes) without using Comparable / Comparator.
    Any suggestion/sample code would be helpful.
    Thanks,
    Sachin

    I suppose you could design another feature to compare Objects... but that would involve a design process, so asking for sample code is definitely premature. And as EJP says, what would be the point?
    At least that's what I would answer if this was one of those stupid interview questions.

  • How can I compare two summary field in cross-tab?

    <p>Dear expert:</p><p>I have one question for how can I compare two summary field in cross-tab?  I have following cross-table:</p><p>Type          Sector1     Sector2    Sector3       Total </p><p>Outlook         10            11           9              30         </p><p>Target            5              3           1               9</p><p>I want to compare the summary field(total) relationship percent, I want to get "9/30". Someone told me I must create the DB view or table via SQL, then can implete in Crystal Report. Can I implete it in Crystal Report via fomula or other function?</p><p>Thanks so much for your warm-hearted help!</p><p>Steven</p>

    Hello Steven, yes you can compare summary fields, If you are comparing Summary to Target, or vice versa - you can do it within Crystal Reports.
    1. In Suppress conditional formula, create 2 Global variables: CurrentOutlook and CurrentTarger and get the current value.
    2. In Display String formula for Total show ToText(CurrentTarget/CurrentOUtlook) + "%".
    For more difficult cases of compariing fields in cross--tab, you may look into http://www.relasoft.net/KB10001.html.
    Best,
    Alexander

  • How to compare two database objects?

    Hi,
    I need to compare two objects with embedded objects/collections in it to tell exact difference between the two.
    e.g.,
    create type t1 as object (name varchar2(10), age number);
    create type t2 as table of t1;
    create type t3 as object (user t1, family t2);
    ... and so on.. this type hirarechy is big in my case..
    I want a procedure/function which can tell me what and where is the difference.
    PROCEDURE (obj1 T1 , obj2 T1) IS
    BEGIN
    END;
    e.g., t1.name = 'John' and t2.name = 'Mich' then it should return t1.name etc..
    Is it possible?
    Thanks

    Why a new thread?
    how to read objects/collections dynamically?

  • How can i compare two excel files with different no. of records.

    Hi
    I am on to a small project that involves us to compare two excel files. i am able to do it but am struck up at a point. When i compare 2 different .csv files with different no. of lines i am only able to compare upto a point till when the number of lines is same in both the files.
    Eg. if source file has 8 lines and target file has 12 lines. The difference is displayed only till 8 lines and the remaining 4 lines in source lines are not shown.
    Can you help me in displaying those extra 4 lines in source file. I am attaching my code snippet below..
    while (((strLine = br.readLine()) != null) && ((strLine1 = br1.readLine())) != null)
                     String delims = "[;,\t,,,|]";
                    String[] tokens = strLine.split(delims);
                    String[] tokens1 = strLine1.split(delims);
                   if (tokens.length > tokens1.length)
                    for (int i = 0; i < tokens.length; i++) {
                        try {
                            if (!tokens.equals(tokens1[i])) {
    System.out.println(tokens[i] + "<----->" + tokens1[i]);
    out.write(sno + " \t" + lineNo1 + " \t\t" + tokens[i] + "\t\t\t\t" + tokens1[i]);
    out.println();
    sno++;
    } catch (Exception exception)
    out.write(sno + " \t" + lineNo1 + " \t\t" + tokens[i] + "\t\t\t\t" + "");
    out.println();
    Thanks & Regards                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    A CSV file is not an Excel file.
    But apart from that your logic makes no sense.
    If the 2 files are of different sizes the files are different by definition, so further comparison isn't needed, you're done.
    If you want to compare individual records, you need to compare all records from one file with all records from the other, unless the order of records is important in which case your current system might work.
    That system however is overly complicated for comparing CSV files.
    As you assume a single record per line, and if one can assume those records to have identical layout (so no leading or trailing whitespace in or between columns in one file that's not in the other) comparing records is simply a matter of comparing the entire lines.

  • How to compare two files in SAP

    Hi All,
    I have downloaded the contents of a custom table in two files and saved in the uncoverted format, now I want to comapre the contents of these files and see if there is any difference in these files or not. So is there any utility in SAP which I can use to compare these two files.
    Thanks,
    Rajeev

    I can think of 3 alternatives -
    1. Write a report to upload the data and then compare the internal table.
    2. Download data in XLS file and use Excel utilities to compare.
    3. Use file compring tools .( Thanks to Thomas - http://en.wikipedia.org/wiki/Comparison_of_file_comparison_tools)

  • How to compare two date Objects

    Hi,
    I have two Calendar Objects, one is coming from client and one is my server time, I need to evaluate that incoming time with server time so that if it is sent before an hour back then i should not do anything on that request Object. I have converted the incoming String into Calendar Object and how can i evaluate these two Calendar Objects including their hours and minutes.
    Thanks in advance
    bajju

    bajjurireddy, ignore Mobiquity's post. It contains no useful information and will only serve to confuse and frustrate you.
    Mobiquity wrote:
    Also make sure that the two date objects are in the same date format..
    public static String DateToDateString(java.util.Date d, String dateFormat)
         throws ParseException {
              SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
              sdf.setLenient(false); // this is required else it will convert
              String dateString = sdf.format(d);
              return dateString;

  • How to compare two files?

    Folks:
    Is there any utility class or method that I can use to compare the contents of two files? Something like diff comamnd in UNIX.
    Thanks a lot!

    I wrote the following program and it seems to work. Any suggestion is welcome!
    import java.io.*;
    public class ContentComparator
    * Returns <code>true</code> if both input streams byte contents is identical.
    * @param input1
    * first input to contents compare
    * @param input2
    * second input to contents compare
    * @return <code>true</code> if content is equal
    boolean contentsEqual( InputStream is1, InputStream is2, boolean ignoreWhitespace )
    try
    if( is1 == is2 )
    return true;
    if( is1 == null && is2 == null ) // no byte contents
    return true;
    if( is1 == null || is2 == null ) // only one has
    // contents
    return false;
    while( true )
    int c1 = is1.read();
    while( ignoreWhitespace && isWhitespace( c1 ) )
    c1 = is1.read();
    int c2 = is2.read();
    while( ignoreWhitespace && isWhitespace( c2 ) )
    c2 = is2.read();
    if( c1 == -1 && c2 == -1 )
    return true;
    if( c1 != c2 )
    break;
    catch( IOException ex )
    finally
    try
    try
    if( is1 != null )
    is1.close();
    finally
    if( is2 != null )
    is2.close();
    catch( IOException e )
    // Ignore
    return false;
    private boolean isWhitespace( int c )
    if( c == -1 )
    return false;
    return Character.isWhitespace( ( char )c );
    public static void main( String[] args )
    InputStream is1 = null;
    InputStream is2 = null;
    try
    is1 = new FileInputStream( "c:\\file1.txt" );
    is2 = new FileInputStream( "c:\\file2.txt" );
    catch( FileNotFoundException e )
    e.printStackTrace();
    ContentComparator cc = new ContentComparator();
    boolean ifIgnoreWhiteSpace = true;
    boolean ifEqual = cc.contentsEqual( is1, is2, ifIgnoreWhiteSpace );
    System.out.println( "Are those two files equal? " + ifEqual );

  • How to compare two file differnces

    Hi All ,
    I have two files on my presentation server one file will have some errors and another will conatine corrected , Now I have to compare those two files and display the differed recoreds as a list.Please provide me the required code.
    Thank you ,
    Satheesh.

    Somebody has thought of this before...
    http://en.wikipedia.org/wiki/Comparison_of_file_comparison_tools
    You don't need a new ABAP program for this.
    Thomas

Maybe you are looking for