1 / 59

Stream Classes in Java: Input & Output

Learn how to handle input and output in Java using Stream classes like BufferedReader and PrintWriter. Understand how to read both string and numerical data efficiently.

mmcgowen
Télécharger la présentation

Stream Classes in Java: Input & Output

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Title Slid CSC 444 Java Programming Input & Output By Ralph B. Bisland, Jr.

  2. Warning Output in Java is UGLY Input in Java Is Very, Very UGLY

  3. Stream: Any input source or output destination. Java provides the Stream classes:BufferedReaderandPrintWriter for input and output respectively. Constructor in BufferedReaderpublic BufferedReader (Reader in); Constructor in PrintWriter public PrintWriter (OutputStream out, boolean autoFlush); Stream Classes

  4. Buffered Reader Hierarchy Diagram Object Reader BufferedReader InputStreamReader

  5. 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

  6. 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 typeReaderwith the type InputStreamReader.

  7. 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.

  8. Buffered Reader (ctd) Hooray!!!! The class java.lang.System contains the constantinof type InputStreamthat represents the standard input stream and corresponds to the keyboard.

  9. Buffered Reader (ctd) Instantiate an object of type InputStreamReaderas 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);

  10. Buffered Reader (ctd) Combining the two statements into one, we get: BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

  11. Print Writer Hierarchy Diagram Object OutputStream Writer FilterOutputStream PrintWriter PrintStream

  12. Print Writer (ctd) public PrintWriter (OutputStream out, boolean autoFlush); Looking at the hierarchy diagram, notice that a class of type OutputStreammay be substituted for a class of type PrintStream. Why make the substitution?

  13. Print Writer (ctd) The class java.lang.System contains a constantoutof typePrintStreamthat represents the standard output stream, and corresponds to the screen. The boolean valueautoFlushcauses the output buffer to be flushed if it is set to true.

  14. Print Writer (ctd) Instantiate an object of type PrintWriter as follows: PrintWriter screen = new PrintWriter(System.out, true);

  15. The class BufferedReadercontains a methodreadLinethat will allow the reading of data type String from the keyboard, by usingkeyboard.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. Input and Output

  16. 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)); Reading String Data

  17. When we want to read into a string variable we use the readLine method. String name; name = keyboard.readLine(); Reading String Data (ctd)

  18. 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.

  19. 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));

  20. 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();

  21. 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.

  22. 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.

  23. Outputting Data (ctd) Before anything is displayed the screen Display must be set up. PrintWriter screen = new PrintWriter (System.out, true);

  24. 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”);

  25. Outputting Data (ctd) To display the current contents of the buffer (flush the buffer). screen.flush();

  26. 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”);

  27. 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();

  28. Outputting Data (ctd) Primitives can be converted to strings by concatenation; int number = 5; screen.println (+ number);

  29. Outputting Data (ctd) Primitives may be concatenated with strings to produce output. float netPay = 1000.0f; screen.println (“Net pay = $” + netPay);

  30. 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!”);

  31. 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.

  32. 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();

  33. 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); } }

  34. 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%

  35. 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”); Reading From Files

  36. UNIX filenames must be specified in the proper case. UNIX filenames may be specified in another directory. (“~bisland/java/data/myfile.dat”) Notes On UNIX Filenames

  37. 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. Notes On PC File Names

  38. 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(). Accessing Data From A File

  39. 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 Sample Program

  40. 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;

  41. 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(); } }

  42. The class FileWriter contains a constructor that requires the pathname of an output file. FileWriter file2 = new FileWriter (“outfile.dat”); Writing Data Out To Files

  43. 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); Writing Data Out to Files

  44. 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. Sample Program

  45. 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);

  46. The Program (ctd) String inline; inline = inputFile.readLine(); while (!inline.equals(“STOP”) { outputFile.println (inline); inline = inputFile.readLine(); } inputFile.close(); outputFile.close(); } }

  47. 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). Tokenizing

  48. To read multiple data items from a single line, we can use methods from the class StringTokenizer in the package java.util. Tokenizing (ctd)

  49. 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(); }

  50. 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. Using StringTokenizer

More Related