O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

174
|
Chapter 4, File Choosers
#32 Preview ZIP and JAR Files
HACK
Note the isTraversable( ) method, which returns true if the file ends with
.zip or is an instance of
ZipEntryFileProxy. Without this, the JFileChooser
would never let the user navigate inside of ZIP files.
Put It All Together
The class in Example 4-4 creates a JFileChooser with a ZipFileSystemView.
The only custom code beyond the view itself is a check to see if the selected
file is a
ZipEntryFileProxy. If so, the program will cast the file to a
ZipEntryFileProxy and call getInputStream( ). If not, it will just create a
FileInputStream
as normal.
As you can see, this method of extending the
JFileChooser to support an
alternative filesystem is quite hackish. Sadly, it’s the only way to do such a
thing without writing a completely custom file chooser. This is probably
why so many IDE authors have just chucked the entire
JFileChooser and
FileSystemView API in favor of a custom dialog. However, if you wish to
remain within the standard API, you can certainly do it, as this hack proves.
As a future enhancement, you might make this class more generic, handling
the nasty details of file wrapping while delegating the actual alternative file-
system to a subclass. This would create an API more like
TreeModel, from
which other developers can create their own implementations easily.
Example 4-4. A sample program
public class ZipTest {
public static void main(String[] args) throws Exception {
FileSystemView fsv = new ZipFileSystemView( );
JFileChooser chooser = new JFileChooser(".");
chooser.setFileSystemView(fsv);
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile( );
System.out.println("Got the file: " + file + " " + file.getClass( ));
InputStream in = null;
if(file instanceof ZipEntryFileProxy) {
in = ((ZipEntryFileProxy)file).getInputStream( );
} else {
in = new FileInputStream(file);
}
// ... code that does something with the InputStream 'in'
}
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required