19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

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

550 Chapter 14 Exception Handling and Text I/O<br />

FIGURE 14.10<br />

JFileChooser can be used <strong>to</strong> display a file dialog for opening a file.<br />

Listing 14.16 gives a program that prompts the user <strong>to</strong> choose a file and displays its contents<br />

on the console.<br />

create a JFileChooser<br />

display file chooser<br />

check status<br />

getSelectedFile<br />

showOpenDialog<br />

APPROVE_OPTION<br />

getSelectedFile<br />

✓Point✓ Check<br />

LISTING 14.16<br />

ReadFileUsingJFileChooser.java<br />

1 import java.util.Scanner;<br />

2 import javax.swing.JFileChooser;<br />

3<br />

4 public class ReadFileUsingJFileChooser {<br />

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

6 JFileChooser fileChooser = new JFileChooser();<br />

7 if ( fileChooser.showOpenDialog(null)<br />

8 == JFileChooser.APPROVE_OPTION) {<br />

9 // Get the selected file<br />

10 java.io.File file = fileChooser.getSelectedFile() ;<br />

11<br />

12 // Create a Scanner for the file<br />

13 Scanner input = new Scanner(file);<br />

14<br />

15 // Read text from the file<br />

16 while (input.hasNext()) {<br />

17 System.out.println(input.nextLine());<br />

18 }<br />

19<br />

20 // Close the file<br />

21 input.close();<br />

22 }<br />

23 else {<br />

24 System.out.println("No file selected");<br />

25 }<br />

26 }<br />

27 }<br />

The program creates a JFileChooser in line 6. The showOpenDialog(null) method displays<br />

a dialog box, as shown in Figure 14.10. The method returns an int value, either<br />

APPROVE_OPTION or CANCEL_OPTION, which indicates whether the Open but<strong>to</strong>n or the<br />

Cancel but<strong>to</strong>n was clicked.<br />

The getSelectedFile() method (line 10) returns the selected file from the file dialog<br />

box. Line 13 creates a scanner for the file. The program continuously reads the lines from the<br />

file and displays them <strong>to</strong> the console (lines 16–18).<br />

14.36 How do you create a File Open dialog box? What is returned from invoking<br />

getSelectFile() on a JFileChooser object?

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

Saved successfully!

Ooh no, something went wrong!