%@ page import="adapt3.*" %> <%! String header, footer; %> <% Adapt a = new Adapt(pageContext); if (header == null) header = a.g("header"); if (footer == null) footer = a.g("footer"); if (request.getMethod().equalsIgnoreCase("GET")) { %>
This section is about reading data from files, and reading data interactively from the keyboard. Along the way, we will develop two template programs:
Lines.java
Echo.java
The first of these counts the number of lines in a file. The classes we
need for doing input from a file are in the java.io package.
Since we may need several of them, we will import the whole package:
// Count the number of lines in a given file.
import java.io.*;
class Lines
{
...
}
The main method does the usual stuff, creating the program
object, checking the number of command line arguments, and calling an initial
method for counting the lines. It also prints out the result message.
// Get the filename from the command line and print the line count
public static void main (String[] args)
{ Lines program = new Lines();
if (args.length != 1)
{ System.out.println ("Usage: java Lines filename");
}
else
{ int n = program.count(args[0]);
System.out.println ("File " + args[0] + " has " + n + " lines.");
}
}
The count method is the one which reads the file:
// Count the lines in a file
int count (String filename)
{ BufferedReader input;
String line;
int n;
n = 0;
input = new BufferedReader (new FileReader (filename));
line = input.readLine();
while (line != null)
{ n++;
line = input.readLine();
}
input.close();
return n;
}
The FileReader object that is created opens the file and
prepares to read characters from it one by one. The
BufferedReader object called input is wrapped round
it, and adds buffering so that text can be read in a line at a time. The
readLine method reads the next line from the file as a string.
When it gets to the end of the file and there are no more lines, it returns
null instead. After the loop, close is called to close
the connection to the file. It is not strictly necessary to do this, because
it is done automatically when the program finishes, but it is 'polite' to call
it as soon as possible to allow other programs access to the file, and it is
good practice so you don't forget in longer-running programs where it becomes
important. For the curious, here is a longer discussion on these I/O
facilites.
Discussion
Copy the program we have developed so far by cut-and-paste or by downloading Lines.java. How many error messages are produced when you compile it? <% a.pl("
"); a.pl(footer); } else { String answer = "4"; String here = "page1.jsp"; String next = "page2.jsp"; String guess = a.getParameter("guess"); if (guess.equals(answer)) response.sendRedirect(next); a.pl("Your answer was"); a.pl("" + guess + ""); a.pl("
The right answer is"); a.pl("
" + answer + ""); a.pl("
Go back and have another look");
a.pl("
Go on to the next page");
}
%>