130 likes | 296 Views
.opennet Technologies Input/Output in Java. Fall Semester 2001 MW 5:00 pm - 6:20 pm CENTRAL (not Indiana) Time Geoffrey Fox and Bryan Carpenter PTLIU Laboratory for Community Grids. Computer Science, Informatics, Physics Indiana University Bloomington IN 47404 gcf@indiana.edu.
E N D
.opennet TechnologiesInput/Output in Java Fall Semester 2001 MW 5:00 pm - 6:20 pm CENTRAL (not Indiana) Time Geoffrey Fox and Bryan Carpenter PTLIU Laboratory for Community Grids Computer Science, Informatics, Physics Indiana University Bloomington IN 47404 gcf@indiana.edu
I/O in Java • Many packages and libraries associated with Java provide sophisticated ways to input and output information, e.g.: • GUI-based approaches: input from low-level keyboard and mouse events, or higher level semantic operations on buttons, menus, etc; outputthrough arbitrarily sophisticated graphics (Swing, AWT, Java2d, etc). • (Server-side) Web-based approaches: input from HTML forms (or via client-side Javascript); output through dynamically generated Web pages (Java Servlets, Java Server Pages, etc). • XML-based: input through XML parsing; output through XML serialization (DOMParser, SAXParser, etc). • Nevertheless, we often need to resort to more traditional methods to read and write information from terminal keyboard and screen, or ordinary files. • This section discusses “traditional I/O”.
Simple Output • We already saw many examples of simple output: e.g. float x ; System.out.println(“The value of x is: ” + x) ; • Here we use the string concatenation operator, + (in conjunction with an implicit “string conversion” operation, which converts x to a suitable String representation). • (Note implicit string conversion only works in a + operation). • The prefix System.out is a reference to a static field of the System class. • System is a class in the implicitly imported java.lang package. • The field out has type PrintStream. It represents the “standard output” of the program. • Typically the terminal screen, unless it has been redirected.
I/O Streams • A stream carries a sequence of bytes or characters. • Stream sources and sinks include: • files • network or thread-to-thread connections • blocks of memory (Java arrays) As far as possible, all types of streams are treated uniformly. • The most basic byte streams are InputStream and OutputStream. These classes have methods to read or write bytes from or to a stream, e.g.: int read(); void write(int); skip(long); available(); flush(); close(); etc, etc • Many of the above methods throw a possible IOException. • The read() and write(int) methods “block” during transfer. • Mostly you won’t use these methods directly: you use higher level methods provided by specialized stream subclasses.
The Output Stream Zoo • The specialized subclasses of OutputStream write their data to specific kinds of target, or offer additional methods to write a byte stream in a more structured way, or provide other functionality, such as guaranteed buffering. • For example, to open a binary stream to an output file, use: FileOutputStream s = new FileOutputStream("/usr/gcf/file"); OutputStream ByteArray OutputStream FileOutput Stream FilterOutput Stream PipedOutput Stream Buffered OutputStream PrintStream DataOutput Stream
FilterOutputStreams • DataOutputStream and BufferedOutputStream are two important FilterOutputStreams. • To open a data stream to an output file, use: DataOutputStream out = new DataOutputStream (new FileOutputStream( filename ) ); where filename is a file name string. • Note that DataOutputStream has methods to write any primitive type. • To open a buffered output stream, use: BufferedOutputStream out = new BufferedOutputStream (new FileOutputStream( filename ) ); • Only bytes may be written to a BufferedOutputStream (unless, say, you create a Dataoutput stream, wrapping it in turn).
The Input Streams • The hierarchy of input streams is follows similar lines to the hierachy of output streams. We don’t reproduce the details here. Check out the Java 2 API at http://java.sun.com/products/j2se/1.4/docs/api
Character Streams • The hierarchies of streams based on InputStream and OutputStream are most suitable for handling “binary” data. • A separate hierarchy of ReaderandWriterclasses fulfill the analogous role for character streams, used to read and write to terminal, or text files. • To construct a character output stream directed to a file, for example: PrintWriter out = new PrintWriter (new FileWriter( filename ) ) ; • Note it is a historical accident that System.out is a PrintStream rather than a PrintWriter. PrintStream is now a deprecated class, and only retained for backward compatibility.
Standard Input/Output • The System class in java.lang provides the “standard” I/O streams System.in, System.out, and System.err. • System.in is an instance of InputStream. • System.out andSystem.err are instances of PrintStream.
Simple keyboard input import java.io.* ; class BufferedReaderTest { public static void main(String [] args) throws IOException { // Create a BufferedReader wrapping standard input: BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; String s ; s = in.readLine() ; // Reads any string terminated by new-line. System.out.println("s = " + s) ; // Print what was read. } }
Wrapper classes for primitive types • Primitive types such as int, char, float, etc. are not classes. Thus one cannot use methods: int var; var.toString(); // Wrong! • However, all primitive types have associated wrapper classes: CharactermyChar = new Character( 'A' ); • The Character class has methods such as: if ( myChar.equals( ch ) ) ... System.out.print( myChar.toString() ); • Static methods in a wrapper class are also useful to convert types, such as a String to a Double.
Example: reading a number double x ; while (true) { // retry loop try { String t = in.readLine() ; // Read line as a string x = Double.valueOf(t).doubleValue() ; // Convert to a double break ; // Success!: break out of retry loop } catch (NumberFormatException e) { System.out.print("Sorry. " + "Please re-enter a double (no spaces): ") ; // retry loop begins again } } System.out.println("x = " + x) ; // Print what was read. • Assumes in set up as in preceding example.
The java.lang.Math class • This class provides standard mathematical functions, using types int, long, float and double. • It is a “static class”, meaning that you only use the static methods. • You cannot create Math objects (enforced by private constructor). • The methods include IEEEremainder, abs, ceil, cos, exp, floor, log, max, min, pow, random, sin, sqrt, and other trig functions. • The random number generator is a linear congruential generator, which is fast but not random enough for many scientific applications.