Sams Teach Yourself Java 6 in 21 Days 5th phần 7 doc

73 307 1
Sams Teach Yourself Java 6 in 21 Days 5th phần 7 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

LISTING 15.3 Continued 39: buff.close(); 40: return true; 41: } catch (IOException e) { 42: System.out.println(“Exception: “ + e.getMessage()); 43: return false; 44: } 45: } 46: 47: boolean readStream() { 48: try { 49: FileInputStream file = new 50: FileInputStream(“numbers.dat”); 51: BufferedInputStream buff = new 52: BufferedInputStream(file); 53: int in = 0; 54: do { 55: in = buff.read(); 56: if (in != -1) 57: System.out.print(“ “ + in); 58: } while (in != -1); 59: buff.close(); 60: return true; 61: } catch (IOException e) { 62: System.out.println(“Exception: “ + e.getMessage()); 63: return false; 64: } 65: } 66: } This program’s output depends on the two arguments specified when it was run. If you use 4 and 13, the following output is shown: Writing: 4 5 6 7 8 9 10 11 12 13 Reading: 4 5 6 7 8 9 10 11 12 13 This application consists of two classes: BufferDemo and a helper class called ArgStream. BufferDemo gets the two arguments’ values, if they are provided, and uses them in the ArgStream() constructor. The writeStream() method of ArgStream is called in line 14 to write the series of bytes to a buffered output stream, and the readStream() method is called in line 16 to read those bytes back. 416 DAY 15: Working with Input and Output Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Even though they are moving data in two directions, the writeStream() and readStream() methods are substantially the same. They take the following format: n The filename, numbers.dat, is used to create a file input or output stream. n The file stream is used to create a buffered input or output stream. n The buffered stream’s write() method is used to send data, or the read() method is used to receive data. n The buffered stream is closed. Because file streams and buffered streams throw IOException objects if an error occurs, all operations involving the streams are enclosed in a try-catch block for this exception. The Boolean return values in writeStream() and readStream() indi- cate whether the stream operation was completed successfully. They aren’t used in this program, but it’s good practice to let callers of these methods know if something goes wrong. Console Input Streams One of the things many experienced programmers miss when they begin learning Java is the ability to read textual or numeric input from the console while running an application. There is no input method comparable to the output methods System.out.print() and System.out.println(). Now that you can work with buffered input streams, you can put them to use receiving console input. The System class, part of the java.lang package, has a class variable called in that is an InputStream object. This object receives input from the keyboard through the stream. You can work with this stream as you would any other input stream. The following state- ment creates a new buffered input stream associated with the System.in input stream: BufferedInputStream command = new BufferedInputStream(System.in); The next project, the ConsoleInput class, contains a class method you can use to receive console input in any of your Java applications. Enter the text of Listing 15.4 in your edi- tor and save the file as ConsoleInput.java. Filtering a Stream 417 15 TIP Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com LISTING 15.4 The Full Text of ConsoleInput.java 1: import java.io.*; 2: 3: public class ConsoleInput { 4: public static String readLine() { 5: StringBuffer response = new StringBuffer(); 6: try { 7: BufferedInputStream buff = new 8: BufferedInputStream(System.in); 9: int in = 0; 10: char inChar; 11: do { 12: in = buff.read(); 13: inChar = (char) in; 14: if ((in != -1) & (in != ‘\n’) & (in != ‘\r’)) { 15: response.append(inChar); 16: } 17: } while ((in != -1) & (inChar != ‘\n’) & (in != ‘\r’)); 18: buff.close(); 19: return response.toString(); 20: } catch (IOException e) { 21: System.out.println(“Exception: “ + e.getMessage()); 22: return null; 23: } 24: } 25: 26: public static void main(String[] arguments) { 27: System.out.print(“\nWhat is your name? “); 28: String input = ConsoleInput.readLine(); 29: System.out.println(“\nHello, “ + input); 30: } 31: } The ConsoleInput class includes a main() method that demonstrates how it can be used. When you compile and run it as an application, the output should resemble the follow- ing: What is your name? Amerigo Vespucci Hello, Amerigo Vespucci ConsoleInput reads user input through a buffered input stream using the stream’s read() method, which returns -1 when the end of input has been reached. This occurs when the user presses the Enter key, a carriage return (character ‘\r’), or a newline (char- acter ‘\n’). 418 DAY 15: Working with Input and Output Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Data Streams If you need to work with data that isn’t represented as bytes or characters, you can use data input and data output streams. These streams filter an existing byte stream so that each of the following primitive types can be read or written directly from the stream: boolean, byte, double, float, int, long, and short. A data input stream is created with the DataInputStream(InputStream) constructor. The argument should be an existing input stream such as a buffered input stream or a file input stream. A data output stream requires the DataOutputStream(OutputStream) constructor, which indicates the associated output stream. The following list indicates the read and write methods that apply to data input and out- put streams, respectively: n readBoolean(), writeBoolean(boolean) n readByte(), writeByte(integer) n readDouble(), writeDouble(double) n readFloat(), writeFloat(float) n readInt(), writeInt(int) n readLong(), writeLong(long) n readShort(), writeShort(int) Each input method returns the primitive data type indicated by the name of the method. For example, the readFloat() method returns a float value. There also are readUnsignedByte() and readUnsignedShort() methods that read in unsigned byte and short values. These are not data types supported by Java, so they are returned as int values. Unsigned bytes have values ranging from 0 to 255. This differs from Java’s byte variable type, which ranges from –128 to 127. Along the same line, an unsigned short value ranges from 0 to 65,535, instead of the –32,768 to 32,767 range supported by Java’s short type. A data input stream’s different read methods do not all return a value that can be used as an indicator that the end of the stream has been reached. Filtering a Stream 419 15 NOTE Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com As an alternative, you can wait for an EOFException (end-of-file exception) to be thrown when a read method reaches the end of a stream. The loop that reads the data can be enclosed in a try block, and the associated catch statement should handle only EOFException objects. You can call close() on the stream and take care of other cleanup tasks inside the catch block. This is demonstrated in the next project. Listings 15.5 and 15.6 contain two programs that use data streams. The PrimeWriter application writes the first 400 prime numbers as integers to a file called 400primes.dat. The PrimeReader application reads the integers from this file and displays them. LISTING 15.5 The Full Text of PrimeWriter.java 1: import java.io.*; 2: 3: public class PrimeWriter { 4: public static void main(String[] arguments) { 5: int[] primes = new int[400]; 6: int numPrimes = 0; 7: // candidate: the number that might be prime 8: int candidate = 2; 9: while (numPrimes < 400) { 10: if (isPrime(candidate)) { 11: primes[numPrimes] = candidate; 12: numPrimes++; 13: } 14: candidate++; 15: } 16: 17: try { 18: // Write output to disk 19: FileOutputStream file = new 20: FileOutputStream(“400primes.dat”); 21: BufferedOutputStream buff = new 22: BufferedOutputStream(file); 23: DataOutputStream data = new 24: DataOutputStream(buff); 25: 26: for (int i = 0; i < 400; i++) 27: data.writeInt(primes[i]); 28: data.close(); 29: } catch (IOException e) { 30: System.out.println(“Error — “ + e.toString()); 31: } 32: } 33: 420 DAY 15: Working with Input and Output Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com LISTING 15.5 Continued 34: public static boolean isPrime(int checkNumber) { 35: double root = Math.sqrt(checkNumber); 36: for (int i = 2; i <= root; i++) { 37: if (checkNumber % i == 0) 38: return false; 39: } 40: return true; 41: } 42: } LISTING 15.6 The Full Text of PrimeReader.java 1: import java.io.*; 2: 3: public class PrimeReader { 4: public static void main(String[] arguments) { 5: try { 6: FileInputStream file = new 7: FileInputStream(“400primes.dat”); 8: BufferedInputStream buff = new 9: BufferedInputStream(file); 10: DataInputStream data = new 11: DataInputStream(buff); 12: 13: try { 14: while (true) { 15: int in = data.readInt(); 16: System.out.print(in + “ “); 17: } 18: } catch (EOFException eof) { 19: buff.close(); 20: } 21: } catch (IOException e) { 22: System.out.println(“Error — “ + e.toString()); 23: } 24: } 25: } Most of the PrimeWriter application is taken up with logic to find the first 400 prime numbers. After you have an integer array containing the first 400 primes, it is written to a data output stream in lines 17–31. Filtering a Stream 421 15 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com This application is an example of using more than one filter on a stream. The stream is developed in a three-step process: 1. A file output stream associated with a file called 400primes.dat is created. 2. A new buffered output stream is associated with the file stream. 3. A new data output stream is associated with the buffered stream. The writeInt() method of the data stream is used to write the primes to the file. The PrimeReader application is simpler because it doesn’t need to do anything regarding prime numbers—it just reads integers from a file using a data input stream. Lines 6–11 of PrimeReader are nearly identical to statements in the PrimeWriter appli- cation, except that input classes are used instead of output classes. The try-catch block that handles EOFException objects is in lines 13–20. The work of loading the data takes place inside the try block. The while(true) statement creates an endless loop. This isn’t a problem; an EOFException automatically occurs when the end of the stream is encountered at some point as the data stream is being read. The readInt() method in line 15 reads integers from the stream. The last several output lines of the PrimeReader application should resemble the following: 2137 2141 2143 2153 2161 2179 2203 2207 2213 2221 2237 2239 2243 22 51 2267 2269 2273 2281 2287 2293 2297 2309 2311 2333 2339 2341 2347 2351 2357 2371 2377 2381 2383 2389 2393 2399 2411 2417 2423 2437 2 441 2447 2459 2467 2473 2477 2503 2521 2531 2539 2543 2549 2551 255 7 2579 2591 2593 2609 2617 2621 2633 2647 2657 2659 2663 2671 2677 2683 2687 2689 2693 2699 2707 2711 2713 2719 2729 2731 2741 Character Streams After you know how to handle byte streams, you have most of the skills needed to han- dle character streams as well. Character streams are used to work with any text repre- sented by the ASCII character set or Unicode, an international character set that includes ASCII. Examples of files that you can work with through a character stream are plain text files, Hypertext Markup Language (HTML) documents, and Java source files. 422 DAY 15: Working with Input and Output Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The classes used to read and write these streams are all subclasses of Reader and Writer. These should be used for all text input instead of dealing directly with byte streams. Reading Text Files FileReader is the main class used when reading character streams from a file. This class inherits from InputStreamReader, which reads a byte stream and converts the bytes into integer values that represent Unicode characters. A character input stream is associated with a file using the FileReader(String) con- structor. The string indicates the file, and it can contain path folder references in addition to a filename. The following statement creates a new FileReader called look and associates it with a text file called index.txt: FileReader look = new FileReader(“index.txt”); After you have a file reader, you can call the following methods on it to read characters from the file: n read() returns the next character on the stream as an integer. n read(char[], int, int) reads characters into the specified character array with the indicated starting point and number of characters read. The second method works like similar methods for the byte input stream classes. Instead of returning the next character, it returns either the number of characters that were read or –1 if no characters were read before the end of the stream was reached. The following method loads a text file using the FileReader object text and displays its characters: FileReader text = new FileReader(“readme.txt”); int inByte; do { inByte = text.read(); if (inByte != -1) System.out.print( (char)inByte ); } while (inByte != -1); System.out.println(“”); text.close(); Because a character stream’s read() method returns an integer, you must cast this to a character before displaying it, storing it in an array, or using it to form a string. Every character has a numeric code that represents its position in the Unicode character set. The integer read off the stream is this numeric code. Character Streams 423 15 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com If you want to read an entire line of text at a time instead of reading a file character by character, you can use the BufferedReader class in conjunction with a FileReader. The BufferedReader class reads a character input stream and buffers it for better effi- ciency. You must have an existing Reader object of some kind to create a buffered ver- sion. The following constructors can be used to create a BufferedReader: n BufferedReader(Reader)—Creates a buffered character stream associated with the specified Reader object, such as FileReader n BufferedReader(Reader, int)—Creates a buffered character stream associated with the specified Reader and with a buffer of int size A buffered character stream can be read using the read() and read(char[], int, int) methods described for FileReader. You can read a line of text using the readLine() method. The readLine() method returns a String object containing the next line of text on the stream, not including the character or characters that represent the end of a line. If the end of the stream is reached, the value of the string returned will be equal to null. An end-of-line is indicated by any of the following: n A newline character (‘\n’) n A carriage return character (‘\r’) n A carriage return followed by a newline (“\n\r”) The project contained in Listing 15.7 is a Java application that reads its own source file through a buffered character stream. LISTING 15.7 The Full Text of SourceReader.java 1: import java.io.*; 2: 3: public class SourceReader { 4: public static void main(String[] arguments) { 5: try { 6: FileReader file = new 7: FileReader(“SourceReader.java”); 8: BufferedReader buff = new 9: BufferedReader(file); 10: boolean eof = false; 11: while (!eof) { 12: String line = buff.readLine(); 13: if (line == null) 424 DAY 15: Working with Input and Output Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com LISTING 15.7 Continued 14: eof = true; 15: else 16: System.out.println(line); 17: } 18: buff.close(); 19: } catch (IOException e) { 20: System.out.println(“Error — “ + e.toString()); 21: } 22: } 23: } Much of this program is comparable to projects created earlier today, as illustrated: n Lines 6–7—An input source is created: the FileReader object associated with the file SourceReader.java. n Lines 8–9—A buffering filter is associated with that input source: the BufferedReader object buff. n Lines 11–17—A readLine() method is used inside a while loop to read the text file one line at a time. The loop ends when the method returns the value null. The SourceReader application’s output is the text file SourceReader.java. Writing Text Files The FileWriter class is used to write a character stream to a file. It’s a subclass of OutputStreamWriter, which has behavior to convert Unicode character codes to bytes. There are two FileWriter constructors: FileWriter(String) and FileWriter(String, boolean). The string indicates the name of the file that the character stream will be directed into, which can include a folder path. The optional Boolean argument should equal true if the file is to be appended to an existing text file. As with other stream-writ- ing classes, you must take care not to accidentally overwrite an existing file when you’re appending data. Three methods of FileWriter can be used to write data to a stream: n write(int)—Writes a character n write(char[], int, int)—Writes characters from the specified character array with the indicated starting point and number of characters written n write(String, int, int)—Writes characters from the specified string with the indicated starting point and number of characters written Character Streams 425 15 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... System.out.println(“Error — “ + e.toString()); 23: } 24: } 25: } 26: 27: class Message implements Serializable { 28: int lineCount; 29: String from, to; 30: Date when; 31: String[] text; 32: 33: void writeMessage(String inFrom, 34: String inTo, 35: Date inWhen, 36: String[] inText) { 37: 38: text = new String[inText.length]; 39: for (int i = 0; i < inText.length; i++) 40: text[i] = inText[i]; 41: lineCount = inText.length;... newInstance(Object[]) method to create a new instance using that constructor Inspecting a Class To bring all this material together, Listing 16. 3 is a short Java application named MethodInspector that uses reflection to inspect the methods in a class LISTING 16. 3 The Full Text of MethodInspector .java 1: import java. lang.reflect.*; 2: 3: public class MethodInspector { 4: public static void main(String[]... Simpo 16: Serializing and Examining Objects PDF Merge and Split Unregistered Version - http://www.simpopdf.com You also can create Class objects by using the forName() class method with a single argument: a string containing the name of an existing class The following statement creates a Class object representing a JLabel, one of the classes of the javax.swing package: Class lab = Class.forName(“javax.swing.JLabel”);... stream File objects are used instead of strings to indicate the files involved, which makes it possible to rename and delete files as needed LISTING 15.8 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: The Full Text of AllCapsDemo .java import java. io.*; public class AllCapsDemo { public static void main(String[] arguments) { AllCaps cap... http://www.simpopdf.com LISTING 15.8 Continued 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: } BufferedWriter out = new BufferedWriter(fw); boolean eof = false; int inChar = 0; do { inChar = in. read(); if (inChar != -1) { char outChar = Character.toUpperCase( (char)inChar ); out.write(outChar); } else eof = true; } while (!eof); in. close(); out.close();... contains the file message.obj and the Message class 441 Object Serialization Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com LISTING 16. 2 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: The Full Text of ObjectReader .java import java. io.*; import java. util.*; public class ObjectReader { public static void main(String[] arguments) { try { FileInputStream... Practice The following question is the kind of thing you could expect to be asked on a Java programming certification test Answer it without looking at today’s material or using the Java compiler to test the code Given: import java. io.*; public class Unknown { public static void main(String[] arguments) { String command = “”; BufferedReader br = new BufferedReader(new InputStreamReader(System .in) ); try {... programming language other than Java Q Can relative paths be used when specifying the name of a file in Java? A Relative paths are determined according to the current user folder, which is stored in the system properties user.dir You can find out the full path to this folder by using the System class in the main java. lang package, which does not need to be imported Call the System class getProperty(String)... represents a String[] array? a java. lang.String b [Ljava.lang.String c [java. lang.String 2 What is persistence? a The capability of an object to exist after the program that created it has stopped running b The ability of a class to support multiple threads c An error-handling technique 3 What Class method is used to create a new Class object using a string containing the name of a class? a newInstance()... asked on a Java programming certification test Answer it without looking at today’s material or using the Java compiler to test the code Given: public class ClassType { public static void main(String[] arguments) { Class c = String.class; try { Object o = c.newInstance(); if (o instanceof String) System.out.println(“True”); else System.out.println(“False”); } catch (Exception e) { System.out.println(“Error”); . 24 37 2 441 24 47 2459 2 4 67 2 473 2 477 2503 2 521 2531 2539 2543 2549 2551 255 7 2 579 2591 2593 260 9 261 7 262 1 263 3 264 7 265 7 265 9 266 3 2 67 1 2 67 7 268 3 268 7 268 9 269 3 269 9 270 7 271 1 271 3 271 9 272 9 273 1. following: 213 7 214 1 214 3 215 3 2 161 2 17 9 2203 22 07 2213 2 221 22 37 2239 2243 22 51 2 2 67 2 269 2 273 2281 22 87 2293 22 97 2309 2311 2333 2339 2341 23 47 2351 23 57 2 371 2 377 2381 2383 2389 2393 2399 2411 24 17. try { 7: BufferedInputStream buff = new 8: BufferedInputStream(System .in) ; 9: int in = 0; 10: char inChar; 11: do { 12: in = buff.read(); 13: inChar = (char) in; 14: if ( (in != -1) & (in !=

Ngày đăng: 13/08/2014, 08:21

Từ khóa liên quan

Mục lục

  • Sams Teach Yourself Java 6 in 21 Days

    • Table of Contents

    • Introduction

      • How This Book Is Organized

      • Who Should Read This Book

      • Conventions Used in This Book

      • WEEK I: The Java Language

        • DAY 1: Getting Started with Java

          • The Java Language

          • Object-Oriented Programming

          • Objects and Classes

          • Attributes and Behavior

          • Organizing Classes and Class Behavior

          • Summary

          • Q&A

          • Quiz

          • Exercises

          • DAY 2: The ABCs of Programming

            • Statements and Expressions

            • Variables and Data Types

            • Comments

            • Literals

            • Expressions and Operators

            • String Arithmetic

            • Summary

Tài liệu cùng người dùng

Tài liệu liên quan