Java Reference
In-Depth Information
Often, we will wish to accept data from the user during the running of a program.
In addition, we may also wish to allow the user to enter a name for the fi le. The next
example illustrates both of these features. Since there may be a signifi cant delay
between consecutive fi le output operations while awaiting input from the user, it is
good programming practice to use File method fl ush to empty the fi le output buffer.
(Remember that, if the program crashes and there is still data in the fi le output buf-
fer, that data will be lost!)
import java.util.*;
public class FileTest2
public static void main(String[] args)
throws IOException
String fi leName;
int mark;
Scanner input= new Scanner(;
System.out.print("Enter fi le name: ");
fi leName = input.nextLine();
PrintWriter output =
new PrintWriter(new File(fi leName));
System.out.println("Ten marks needed.\n");
System.out.print("Enter mark " + i + ": ");
mark = input.nextInt();
//* Should really validate entry! *
output.fl ush();
Example output from this program is shown in Fig. 4.1 .
When reading data from any text fi le, we should not depend upon being able to
read a specifi c number of values, so we should read until the end of the fi le is reached.
Programming languages differ fundamentally in how they detect an end-of-fi le situ-
ation. With some, a program crash will result if an attempt is made to read beyond the
end of a fi le; with others, you must attempt to read beyond the end of the fi le in order
for end-of-fi le to be detected. Before Java SE 5, Java fell into the latter category and
it was necessary to keep reading until the string read (and only strings were read then)
Search WWH ::

Custom Search