Ooh … Begitu! I see, I see …

Icon

Setelah kelayapan di internet, cari-cari info dari sana-sini dan bongkar pasang tips (terutama programming), akhirnya baru sadar … ternyata begitu caranya … [all about tricks and tips I have found during my work as programmer.]

how to check if two filename paths refer to the same file?

I just found out the information that a filename path may include redundant names such as ‘.’ or ‘..’ or symbolic links (on UNIX platforms).
so how to know exactly if two filename paths are referring to the same file?

use File.getCanonicalFile() to convert a filename path to a unique canonical form suitable for comparisons. and then, compare the results of both getCanonicalFile() with equals(…)

just take a look at this example below to get some idea.

    public boolean isSameFile() {
        File file1 = new File("./filename");
        File file2 = new File("filename");
        
        // Filename paths are not equal
        // false, don't use this way to compare.
        boolean b = file1.equals(file2);                
        
        // Normalize the paths first.
        try {
            // D:\\sth\\filename
            file1 = file1.getCanonicalFile(); 

            // also D:\\sth\\filename
            file2 = file2.getCanonicalFile(); 
        } catch (IOException e) {
            // your exception lines...
        }
        
        // Filename paths are now equal.
        return file1.equals(file2);              // true
    }

I got this information from www.exampledepot.com there are more interesting tips about file handling in Java programming. just make sure you won’t miss those tips too. šŸ™‚

have a nice day of coding.

Advertisements

Filed under: Java programming, , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives

%d bloggers like this: