Java Reference
In-Depth Information
and following blanks, with this statement:
i= Integer.parseInt(br.readLine().trim());
The other wrapper classes have their equivalents of parseInt . For example,
to extract a double value from a string line use:
double d= Double.parseDouble(line.trim());
Iteration with input
You may want to read and process keyboard input lines until some stopping
condition is met, e.g. some line contains the word "quit" . This kind of task is
usually done with a loop . If you know about loops, writing such a loop will be
easy. See Chap. 7 for a discussion of loops.
import javax.swing.*;
/** Illustrate use of class JFileChooser and reading a file */
public class FileChooserApp {
public static void main(String[] args) throws IOException {
BufferedReader br= getReader(); // A link to the user's file
if (br == null ) { return ; }
// Read file br and print the length of each line
String s= br.readLine();
// { inv: s is last line read and lengths of lines before line s have been printed }
while (s != null ) {
s= br.readLine();
/** Obtain a file name from the user, using a JFileChooser , and return a reader that
that is linked to it. If the user cancels the choice, return null */
public static BufferedReader getReader() throws IOException {
JFileChooser jd= new JFileChooser();
jd.setDialogTitle("Choose input file");
jd.showOpenDialog( null );
File f= jd.getSelectedFile();
if (f == null ) { return null ; }
return new BufferedReader( new FileReader(f));
Figure 5.6:
Read lines from a file selected by user and print their lengths
Search WWH ::

Custom Search