dev@glassfish.java.net

Re: File IO tip

From: Byron Nevins <Byron.Nevins_at_Sun.COM>
Date: Thu, 29 May 2008 17:21:09 -0700
The bottom of the email has the bug I filed against the JDK....

Tim Quinn wrote:
Hey, Byron.

There is a whole set of new path-related classes and methods proposed for Java 7.  I'd suggest you file a bug against Java 6 for this.  I doubt anything will happen to the File class and the methods you've described, but it might help make sure that the new path-related APIs do the right thing.

- Tim

Lloyd L Chambers wrote:
Thanks Byron, a good tip.

On May 17, 2008, at 11:04 AM, Byron Nevins wrote:

Say you are given a java.io.File object that was made like so:

File f = new File("/foo/./././goo");

Say that you need a File object for the parent dir -- which is "/foo" in this case.

If you do this:

File parent = f.getAbsoluteFile().getParentFile()

parent will be "/foo/././"
File grandparent = parent.getParentFile()

grandparent will be "/foo/."

I.e. getParent and getParentFile are pretty dumb.  They just strip off the last path seperator without looking at it.

Now if you do the following with the original file, you get the "real" parent dir.  This is the trick.

File parent = new File(f, "..");
parent --> "/foo"

------------------------------
I.e. never call getParent or getParentFile -- it will not work with relative path portions.
instead use the File constructor with ".." as the filename.
-------------------------------

Another possible solution is to sanitize the original File with getCanonicalFile() to get rid of the relative path portions.
this has 3 problems -

1) Your path will have error-prone and unneccessary (usually) backslashes in Windows
2) It's more work and requires a try/catch block
3) It handles symbolic link files differently

The reason I'm sending this tip out is that I got burned by this behavior.  I had code that was getting a crucial parent directory.  It was working fine for months.  Then in code a hundred levels above it, a "." was inserted just before the final directory name.  KABOOM. 

Ref: http://bt2ws.central.sun.com/CrPrint?id=6687287
-- 
Byron Nevins Work 408-276-4089, Home 650-359-1290, Cell 650-784-4123 - Sun Microsystems, Inc.

---
Lloyd L Chambers
Sun Microsystems, Inc




-- 
Byron Nevins Work 408-276-4089, Home 650-359-1290, Cell 650-784-4123 - Sun Microsystems, Inc.