Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Title Slid CSC 444 Java Programming Input & Output By Ralph B. Bisland, Jr. Warning Output in Java is UGLY Input in Java Is Very, Very UGLY 2 Stream Classes • Stream: Any input source or output destination. • Java provides the Stream classes: BufferedReader and PrintWriter for input and output respectively. • Constructor in BufferedReader public BufferedReader (Reader in); • Constructor in PrintWriter public PrintWriter (OutputStream out, boolean autoFlush); 3 Buffered Reader Hierarchy Diagram Object Reader BufferedReader InputStreamReader 4 BufferedReader public BufferedReader (Reader in); To instantiate an object of type BufferedReader it is necessary to supply the constructor with the correct type (Reader). Note that Reader is a superclass of InputStreamReader 5 Buffered Reader (ctd) Remember that an object lower down a class hierarchy to be passed as an argument to a method that requires a parameter of a class further up the class hierarchy. Can substitute type Reader with the type InputStreamReader. 6 Buffered Reader (ctd) Constructor from the class InputStreamReader: public InputStreamReader (InputStream in); Now we need to find a constant that represents the standard input stream. 7 Buffered Reader (ctd) Hooray!!!! The class java.lang.System contains the constant in of type InputStream that represents the standard input stream and corresponds to the keyboard. 8 Buffered Reader (ctd) Instantiate an object of type InputStreamReader as follows: InputStreamReader stream = new InputStreamReader (System.in); The object stream may be used to instantiate the object keyboard as follows: BufferedReader keyboard = new BufferedReader (stream); 9 Buffered Reader (ctd) Combining the two statements into one, we get: BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); 10 Print Writer Hierarchy Diagram Object OutputStream Writer FilterOutputStream PrintWriter PrintStream 11 Print Writer (ctd) public PrintWriter (OutputStream out, boolean autoFlush); Looking at the hierarchy diagram, notice that a class of type OutputStream may be substituted for a class of type PrintStream. Why make the substitution? 12 Print Writer (ctd) The class java.lang.System contains a constant out of type PrintStream that represents the standard output stream, and corresponds to the screen. The boolean value autoFlush causes the output buffer to be flushed if it is set to true. 13 Print Writer (ctd) Instantiate an object of type PrintWriter as follows: PrintWriter screen = new PrintWriter(System.out, true); 14 Input and Output • The class BufferedReader contains a method readLine that will allow the reading of data type String from the keyboard, by using keyboard.readLine(). • You may only read data of type String using readLine. • How do you read data if type int, float, long, etc.? • Input the number as a string and use the appropriate wrapper class to do the conversion. 15 Reading String Data • Since all input is read as a string, reading string data is fairly simple. • Before reading data into a string we must set up for a buffered read. BufferedReader keyboard = new BufferedReader (new inputStreamReader (System.in)); 16 Reading String Data (ctd) • When we want to read into a string variable we use the readLine method. String name; name = keyboard.readLine(); 17 Reading Numeric Data To read a value and convert it we must use the Wrapper class. Integer class has a constructor method, Integer (String S)that converts a String to an Integer. 18 Reading Numeric Data (ctd) Example: new Integer (keyboard.readLine()) creates an object of type Integer. Before converting we must set up for a buffered read. BufferedReader keyboard = new BufferedReader (new inputStreamReader (System.in)) 19 Reading Numeric Data To convert read an input string and convert it an int. BufferedReader keyboard = new BufferedReader (new inputStreamReader(System.in)); int number; number = new Integer (keyboard.readline()).intValue(); 20 Reading Numeric Data (ctd) To read a string and convert it to a floating point: fltnumber = new Float (keyboard.readLine()).floatValue(); Remember all primitives have wrapper classes. 21 Outputting Data Outputting data is much simpler than inputting data. The class PrintWriter contains methods for displaying data as strings. The methods are: print, println, and flush. 22 Outputting Data (ctd) Before anything is displayed the screen Display must be set up. PrintWriter screen = new PrintWriter (System.out, true); 23 Outputting Data (ctd) To display a string on the screen and then move the cursor to the next output line. screen.println (“Guardez loo”); To display a string on the screen and leave the cursor at the end of the line. screen.print (“Hold ye hand”); 24 Outputting Data (ctd) To display the current contents of the buffer (flush the buffer). screen.flush(); 25 Outputting Data (ctd) Strings may be output using Unicode format: screen.println (“\u0041\u0042\u0043”); Escape sequences may be used to format data: \t = Display data at the next tab stop. \n= New line screen.println (“Ralph\nBisland”);26 Outputting Data (ctd) To display string variables: String name = “Ginny Fleck”; screen.println (name); Strings can be concatenated: screen.print(“Hi there: “ + name); screen.printLn(); 27 Outputting Data (ctd) Primitives can be converted to strings by concatenation; int number = 5; screen.println (+ number); 28 Outputting Data (ctd) Primitives may be concatenated with strings to produce output. float netPay = 1000.0f; screen.println (“Net pay = $” + netPay); 29 A Quick and Dirty Print Can still use the print or println method from the System package to write data out. System.out.println (“Guardez des loo!!”); System.out.print (“Hold “) System.out.print (“ye “); System.out.println (“hand!”); 30 Simple Problem Write a Java program to read a string of characters from the Keyboard, print out the input string, convert the string to an array of characters, print out the array of characters, then convert The array of characters back to a string and display the new string. 31 SimpleStringRead.java orca% cat SimpleStringRead.java import java.io.*; class SimpleStringRead { static PrintWriter scr = new PrintWriter(System.out,true); static BufferedReader kb = new BufferedReader (new InputStreamReader(System.in)); public static void main (String [] args) throws IOException { String str; scr.print ("Enter a string: "); scr.flush(); str = kb.readLine(); 32 SimpleStringRead.java (ctd) scr.println ("String: " + str); // // Convert string to an array of characters // char[] aoc = str.toCharArray(); for (int i = 0; i < aoc.length; i++) scr.println ("aoc[" + i + "] = " + aoc[i]) // // Convert array back to a string // String str2 = String.valueOf(aoc); scr.println ("Converted string: " + str2); } } 33 SimpleStringRead.java (ctd) orca% javac SimpleStringRead.java orca% java SimpleStringRead Enter a string: abcde String: abcde aoc[0] = a aoc[1] = b aoc[2] = c aoc[3] = d aoc[4] = e Converted string: abcde orca% 34 Reading From Files • Instead of reading from the keyboard we now want to be able to read from an ASCII text file. • A file must be “opened” before it can be read from. • The class FileReader contains a constructor that requires the pathname (path and filename) of an input file. FileReader file = new FileReader (“indata.dat”); 35 Notes On UNIX Filenames • UNIX filenames must be specified in the proper case. • UNIX filenames may be specified in another directory. (“~bisland/java/data/myfile.da t”) 36 Notes On PC File Names • PC files may be specified in other subdirectories and/or disks. (“a:\\java\\data\\myfile.dat”) • Note the use of double backslashes to avoid confusion with escape sequences. 37 Accessing Data From A File • To provide the same method that was used with keyboard input (readLine) it is necessary to use the object file in the constructor of the BufferedReader; thus creating a stream object inputFile that is associated with reading from a disk file with the pathname (“mydata.dat”). BufferedReader inputFile = new BufferedReader (file); • The instance method to close a file defined in the class BufferedReader is close(). 38 Sample Program • Write a Java program to read in student’s names and GPA’s, stored in the UNIX file called stu.dat and display them on the screen. • The data file is formatted as follows: GPA of student1 name of student 1 GPA of student 2 name of student 2 . . . 0 39 The Solution // Documentation goes here import java.io.*; class Gpas { static PrintWriter scr = new PrintWriter (System.out, true); public static void main (String [] args) throws IOException { FileReader file = new FileReader (“mydata.dat”); BufferedReader inputFile = new BufferedReader (file); String name; float gpa; 40 Program (ctd) gpa = new Float(inputFile.readLine()).floatValue(); while (gpa != 0.0f) { name = inputFile.readLine(); scr.printLn(gpa + “\t” + name); gpa = new Float(inputFile.readLine()).floatValue(); } inputFile.close(); } } 41 Writing Data Out To Files • The class FileWriter contains a constructor that requires the pathname of an output file. FileWriter file2 = new FileWriter (“outfile.dat”); 42 Writing Data Out to Files • To provide the same methods that were used with screen output (print, println, flush) it is necessary to use the object file2 in the constructor of the PrintWriter; thus creating a stream object outputFile that is associated with the writing to the disk file with the pathname “outfile.dat”. PrintWriter outputFile = new PrintWriter (file2); 43 Sample Program • Write a Java program to read a UNIX text file and copy it’s contents to another UNIX text file. • The input file is called “input.dat”. • The output file is called “output.dat”. • The last line of the input file contains the word STOP. 44 The Program // Insert documentation here import java.io.*; class ReadWrite { public static void main (String [] args) throws IOException; { FileReader file1 = new FileReader (“input.dat”); BufferedReader inputFile = new BufferedReader (file1); FileWriter file2 = new FileWriter (“output.dat”); PrintWriter outfile = new PrintWriter (file2); 45 The Program (ctd) String inline; inline = inputFile.readLine(); while (!inline.equals(“STOP”) { outputFile.println (inline); inline = inputFile.readLine(); } inputFile.close(); outputFile.close(); } } 46 Tokenizing • Text files with one data item per input line are generally inefficient and useless. • A token is a data item delimiter by some character(s). Examples: Space(s), comma, End of line marker, etc. • Whitespace is defines as either: a space (\0020), horizontal tab (\u0009), new line (\u000A), vertical tab (\u000B), or form feed (\u000C). 47 Tokenizing (ctd) • To read multiple data items from a single line, we can use methods from the class StringTokenizer in the package java.util. 48 StringTokenizer Class public class StringTokenizer implements enumeration { public StringTokenizer (String str, String delim, boolen returnTokens); public StringTokenizer (String str, String delim); public Stringtokenizer (String str); public boolean hasMoretokens(); public String nextToken(); public String nexttoken(String delim); public boolean hasMoreElements(); public Object nextElement(); public int countTokens(); } 49 Using StringTokenizer • To use StringTokenizer, it must be instantiated from the input string. StringTokenizer data = new StringTokenizer(inputFile.readLine()); • A line can only be split into tokens if we know what the delimiting character is for each token. • Example: Lines of text are delimited by a return character and data items are separated by a blank space. • If the token delimiter is not specified, the delimiter is assumed to be whitespace. 50 Using StringTokenizer (ctd) • Both nextToken methods return a token of type String. • The method nextToken() assumes a delimiter of whitespace. String token = data.nextToken(); • The method nextToken (String delim) allows the user to specify the delimiter. String token = data.nextToken(“\u000A”); • The method countTokens() returns the number of tokens in a string that are delimited by whitespace. 51 Example Program • Read in two tokens from the keyboard. • The tokens are separated by whitespace. • Print out the original string containing the input line. • Print out each taken on a separate output line. 52 StringTokenizerRead.java orca% cat StringTokenizerRead.java import java.io.*; import java.util.*; class StringTokenizerRead { static PrintWriter scr = new PrintWriter(System.out,true); static BufferedReader kb = new BufferedReader (new InputStreamReader(System.in)); //--------------------------------------------- 53 StringTokenizerRead.java (ctd) public static void main (String [] args) throws IOException { String data = kb.readLine();// Read the line scr.println (data); // Print the line StringTokenizer st = new StringTokenizer (data); // Tokenize String buf = st.nextToken();// Get 1st token scr.println (buf); // Print 1st token buf = st.nextToken(); // Get next token scr.println (buf); // Print next token } } 54 StringTokenizerRead.java(ctd) orca% javac StringTokenizerRead.java orca% java StringTokenizerRead one two one two one two orca% 55 Example Program Write a Java program to read a text file and count the number of words in file. A word is a group of characters delimited by whitespace. End of file is indicated by two return characters. Upon reading the first return, the number of tokens will be zero. 56 Program //Documentation goes here import java.io.*; import java.util.*; class CountWords { static PrintWriter scr = new PrintWriter (System.out, true); public static void main (String[] args throws IOException { FileReader file = new FileReader(“indata.dat”); BufferedReader inputFile = new BufferedReader (file); StringTokenizer data; int numberOfTokens; int numberOfWords = 0; 57 Program (ctd) data = new StringTokenizer(inputFile.readLine()); numberOfTokens = data.countTokens(); while (numberOfTokens != 0) { for (int words=1; words <= numberOfTokens; words++) { scr.print(data.nextToken() + “ “); scr.flush(); } scr.printLn(); numberOfwords=numberOfWords+numberOfTokens;; data = new StringTokenizer(inputFile.readLine()); 58 Program (ctd) numberOfTokens = data.countTokens() } scr.println(“\nThere are “+numberOfWords+ ” words in the file.”); } } 59