23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Java</strong> I/O<br />

Example 13.1 is a program that presents an open file dialog to the user, then writes the<br />

contents of the file they selected on System.out. There are many good ways to do this. I<br />

chose to write a static getFile() method that returns a File object; then open and print this<br />

file back in the main() method.<br />

Example 13.1. The FileTyper Program<br />

import java.io.*;<br />

import java.awt.*;<br />

import com.macfaq.io.*;<br />

public class FileChooser {<br />

}<br />

public static void main(String[] args) {<br />

try {<br />

File f = getFile();<br />

if (f == null) return;<br />

FileInputStream fin = new FileInputStream(f);<br />

StreamCopier.copy(fin, System.out);<br />

}<br />

catch (<strong>IO</strong>Exception e) {System.err.println(e);}<br />

// Work around annoying AWT non-daemon thread bug.<br />

System.exit(0);<br />

}<br />

public static File getFile() throws <strong>IO</strong>Exception {<br />

}<br />

// dummy Frame, never shown<br />

Frame parent = new Frame();<br />

FileDialog fd = new FileDialog(parent, "Please choose a file:",<br />

FileDialog.LOAD);<br />

fd.show();<br />

// Program stops here until user selects a file or cancels.<br />

String dir = fd.getDirectory();<br />

String file = fd.getFile();<br />

// Clean up our windows, they won't be needed again.<br />

parent.dispose();<br />

fd.dispose();<br />

if (dir == null || file == null) { // user cancelled the dialog<br />

return null;<br />

}<br />

return new File(dir, file);<br />

File dialogs only allow the user to select ordinary files, never directories. If you want to ask<br />

users to pick a directory, you have to ask them to choose a file in that directory, then call<br />

getDirectory(). (This workaround fails with empty directories.) Here's an alternative<br />

main() method for the DirList program given in Example 12.5 that uses a file dialog to<br />

select the directory to list rather than command-line arguments:<br />

309

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!