Sei sulla pagina 1di 14
UNIT3 [45 asiinputetputsteam 3.4 Filter Streams Objectives 1, Explain stream filcering for data conversion, 2. Describe the data conversion. Introduction Earlier in the unit, we said that there were basically wo stream categories — byte streams and character streams. According to the directions of the data flow in the screams, they were further classified into input stream and oucpuc stream, as shown in Table 3.4 Byte steam TGhancte rear input | Inporstesam (e.3- Reader stream_| Fs iernpoeseream (eugus FiteResder) Output | outputstrean weiter steam | (o.9., eilooutputsteean) | (e.g. Pileieiter) Table 3.4 The different categories of stream classes “The classes shown in parentheses in Table 3.4 are concrete subclasses of the general classes Tnputstrean, Reader, OutputStream and tri ter and are dedicated to file inpuv/outpue operations. Besides concrete clases for performing the input/output operations with a particular data source or data destination, the Java standard softwate library provides classes that act as an intermediary providing extra functionalities ‘The Java standard software library provides some classes that do not associate with particular storage media or communication channels but with the general input stream and ousput stream. For an input filter stream object, it reads daca from ics associated input stream co be returned with extra functionality. Similarly, the output filter stream object manipulates the data supplied to it for extra functionality, and the resultant data are sent co its associated output stream object. Figure 3.22 can help you to visualise the relationship beoween filter streams and general input/output 446) WAWASAN OPEN UNIVERSITY CC102 Computing t read data foytes) extra functionality byread() method forreading data ee vite data (bytes) extra functionality for writing data bywriter) method Sarna | Figure 3.22 The functionalities of filter streams ‘The Java software library provides many filter classes, The commonly used filter classes ate for data conversion and improving execution performance. In the next subsection, we discuss possible filer streams for data conversions. To improve input! output operating performance, a possible way is to use the computer's memory as a temporary data source and data destination, because accessing computer memory is much faster than accessing secondary memory such as file. Filter streams for conversion A common unit of data flow ina computer is an 8-bit byte. Therefore, the basic units of data for most storage media and communication channels ae of type byte aswell. However, a software application may require collection of bytes to represent some more structured data, such as ic takes 4 bytes and 8 bytes ina storage device to represent a 4-byte integer value of type int and an S-byte data item of type eoupie. With an Inputstream object, itis possible to tead 4 bytes and 8 bytes in the program and convert them programmatically into data of int and double respectively. tis a common but tedious task. Therefore, the Java standard software library provides clases for conversions between bytes and the structured data based con the idea of filter streams, The data conversions Different computers had no way to communicate with one another, Each computer ‘manufacturer had its own way of representing letters in the alphabet, numbers and ‘control codes. Therefore, the American Standard Code for Information Interchange (ASCII) functions as 2 common denominator between computers that otherwise have nothing in common. It works by assigning standard numeric values co leevers, numbers, punctuation marks and other characters such as control codes. ‘An uppercase “A,” for example, is represented by the number 65. “Amongall daca conversions, the conversion between 8-bit bytes and 16-bit characters js the most common. You should note the JVM handles characters in Unicode, which UNITS [47 Basicinpatiotput stream is a 16-bit coding system. That is, each character needs 16 bits ro represent it. For 4 storage medium such as a file on a disk, a character in a text file rakes 8 bits or 16 bits to represent it depending on the code of the character and the defaule coding system of the platform. Furthermore, the codes for the same character in the default coding system of the platform (mostly an 8-bit coding system) and Unicode may differ. Therefore, a translation between 8-bit byte and 16-bit Unicode character is required in reading and writing character daa to and from a data source/destination, as shown in Figure 3.23. Input operation Output operation -———, byte aM Co ———— source ‘Unicode char Figure 3.23 The input/output operations with respect to the JVM. ‘Whenever a character data item flows across the boundary of the JVM, itis usually necessary to perform a translation between byte and character. For example, if the contents ofa file are it is expected that when the data are read from the file, shey are converted into a sequence of characters such as My oe You should note that every single byte in the fileis converted into a wo-byce Unicode character. Going the other way, you would expect that when a sequence of characters is written to a byte-oriented destination stream, the data would be converted into byzes and stored properly ‘T illustrate che necessity of data conversion, Lee's create a text file with an editor software such as Notepad. The TestBinaryFileviewer program will read the file. ‘Type something in the file, such as: hl tenWhese ee File Edit Format 48 WAWASAN OPEN UNIVERSITY TEC 102 Computing Save the ilewith a name, say ‘openu,tat’.Then, wecan use the TestBinaryFileVionor ")? ) else { // Create a TextPilelriter object ‘TextPileWriter creator = new TextFileWriter(); // Create the File with the message according to parameter creator-create(args{0), args(1})> Figure 3.25 ArgsToFilejava ‘Compile the classes and execute the ArgsToF ile program as shown in Figure 3.24 and Figure 3.25 50| WAWASAN OPEN UNIVERSITY | rec 102 Computing t Le program creates a file ‘out-xt’ and the String object “e110 or2a" is written to it (If che message supplied via the second program parameter contains a single word, the pair of double quotation marks is optional.) The file size of the created file ‘our.txt is 11. Fxecute the TestBinaryeileviewer with ‘ourext as program parameter. The following output is shown Command Prompt RU nt gest reese Ge ee Cree seat ip cere tree irote otter nace Ss Figure 3.26 Compile and then execute ArgsTofilejava. Then you will get the output. You can sce that every time the wzite() method is called and a character (a daa item of primitive type char) is supplied, the data eventually written to the data destination (che file in this case) area single byte forall characters defined in ASCIL This confirms that a translation process is involved, and it determines that a eo byte character that corresponds to a character defined in ASCII is translated and written to the data destination as a single byte. QO Every objece that ourpurs data t0 a byte stream belongs to one of the subclasses of the abstract class OutputStream. Objects that read data from a byte stream belong to subclasses of trputStzean. Ifyou write numbers to an Ostpatsereen, you will not be able to read the resulting data yourself But the data can be read back into the computer with an Toputstream. The writing and reading of the data will be very efficient, since there is no translation involved: the bits that are used to represent the data inside the computer are simply copied to and from the streams, For reading and writing human-readable character data, the main classes are Reade and ieitex, All character stream classes are subclasses of one of these. Ifa number is co be written to a writer stream, the computer must translate it into a human-readable sequence of characters that ‘represents that number. Reading a numbet from a Reader stream into a numeric variable also involves a translation, from a character sequence into the appropriate bie string. UNIT3 [51 Basiciaptoutptsteam 3.5 The Standard Input and Standard Output Objectives 1. Manipulate standard input from keyboard. 2, Manipulate message for standard output Introduction We have been using statements that look like systen.out.printin ar): to display the contents of che variable on the screen since che first program you ‘encountered in the course. But we have not discussed why and how it works, The variable out: is a class (static) variable of the java.1ang.System (or simply systen) clas, Also, the class defines another class variable, in, which can be used for input purposes. ‘The two class variables in, and out represent the standard inpuc stream and standard owipuet stream respectively. The type of the class variable in is tnputstreamand the types of the class variables out is Printstrean. As they are publ ic class vatiables, it is possible to access them directly, such as: systen.out.peintia(); When the JVM is launched, an 1nputstream object attached ro the computer keyboard is prepared and is referred by the class variable in of the system class. The printstream object are prepared and are made accessible by class variables out of the system class. Iris usually used for displaying application related messages. In the following subsection, we discuss how co manipulate these stteams for performing input/output operations. Reading entries from a keyboard ‘We mentioned that when the JVM is tarred, an tnputstxeam object thats attached to the keyboard of the computer is prepared by default, and itis made accessible via the class variable in of the system class. Therefore, itis possible to use the ead () method of the Tnput stream object to retrieve the byte obtained from the attached keyboard. 52] WAWASAN OPEN UNIVERSITY HEC102 Computing Reas 1g bytes from a keyboard [A class Keyboard is written in Figure 3.27 to illustrate how to retrieve a byte from the computer keyboard // Resolve clases in java.io package Amport java.io.*; public class Keyboardi // Constant for end of file private static final int EOP = -1; // Show the entries from keyboard public void ehow() throws TOException | int byteCount = 07 // The count of byte read int byteRead; // The byte read trom keyboard // R while loop to read a byte from the keyboard while ((byteRead = Syetem.in.read()) != EOF) ( // Increase the byte count bytecountt+s // Show the byte read System.out.print (“Byte (4” + bytecount +") = + byteRead) ; // 18 the byte read is treated as a character and its // code is qzeater than 31, show it, Otherwise, just skip to // next new Line. Af (byteRead > 32) | System.out.printin(* <" + (char) bytoRead + “>"); } else | systen-out-printin (07 Figure 3.27 Keyboard! java ‘The driver program, resteyboaral, is shown in Figure 3.28. // Reselve classes in java.io package import java.io.* public class TestKeyboardl | public static void main(String arge[}) throws TORxception ( // Show message for terminating the program Systen-out.printia ("Eater Ctrl-z/Ctrl-D to terminate program"); // Create a Keyboardl object Keyboard] keyboard ~ new Keyboardl () Le UNIT3 [53 Bascinpuvoutput stream | J) Show the entry from the keyboard keyboard. show(): ) Figure 3.28 Testkeyboard1 java Compile the classes and execute the Test¥eyboardt class. The following message Teen \JavaFiles\TCC1@2Unit3>java TestKey (ees eyes rca isshown on the screen, and the progeam is waiting for your entry from the keyboard. ‘The program will repeatedly get che codes of the keystrokes from the keyboard. ‘To terminate the program, itis necessary to enter a special keystroke representing, the end of entry, For the Windows family and UNIX platforms, the keystrokes are ctel-z (or #6) and cer1-D respectively. ‘When you type a non-control key, such as 2 letter, a number or 2 symbol on your keyboard, the charactet is shown on the screen. Before pressing the key, you can even use the keys, cbackspace> and key to navigace among the characters typed and modify them. For example, the keys to are typed, that i Guu encore cll Piles\TCC102Unita>javac TestKeyboardi .java eee CoC SRC Ceca ett e (Bie sakes ores ere rt La cd EU) Riera ‘Then, you can press the key to terminate a line of entry, and the program will show the following message according to the entry Se 54] WAWASAN OPEN UNIVERSITY TEC102 Computing t You can see that the line of entry contains seven letters, and the output message shows that nine bytes arc read. The last two bytes are the default byte pattern of the default end of line of the platform, which is the same as the defaule end of line for text fils. Displaying messages to standard output ‘We have been using the statement Systom.out.printin (var) s co display the contents of the variable vax to the screen without being concerned how the statement works. First, even if you did not know the term System in the above statement refers to the class 3ava.lang.Systom you should notice that according to the naming convention of Java, the term system, which starts with a capital leter, is nota variable name but a class name. Then, the term system.out indicates that the variable out isa class variable of the class System. Furthermore, as ic is possible to refer to the variable out in any class, che class variable out is public class variable of the class Systen. By defaule, the standard ourput device sends the output to a device driver attached to the screen, However, the output destination can be redirected to a device driver attached toa file or printer, which results in che same program displaying is findings on the screen, saving them in a file, or providing a hard copy listing of the results You achieve standard output by calling Java's System.out print () and systen.out -printn() methods. Except for the fact that print () methods do nat ‘output a new-line character after the data, the ewo method groups are equivalent. Methods exist to ouput Boolean, character, characterarray, double-precision floating- point, floating-point, integer, long integer, string, and object values. To demonstrate these methods, Figure 3.29 presents source code to the Print application. If print. java clase Print [ public static void main (String {] args) ( boolean b = trues System-out.priatin (5) char c= ‘A system.out.printin(c) char {) cazeay = ( A", *BY, System.out.printin(carray); double d = 3.57 system.out-printinid); float f ~ ~9.35; System.ovt-peiatin (#1; ants = Ks system.out-printinli)s ong 1 = 9000000, UNITS /55 Bascinpuvouput stream | system-out printin (1); String @ = “abe”; System-out.priatin(s) system.out printin(new Print ())s Figure 3.29 Printjava Figure 3.29 has probably criggered some questions for you. First, what is all that System. out. business doing in front of printin (1? Again, refer to the system class in the SDK documentation. The class contains a variable called out — an object created froma class called 2int steam. The period character after System indicates that out belongs ro System. The period character after out states that print1n() belongs to out. In other words, printin() isa method that belongs to an object called out, which in turn belongs oa class called systen. ‘The second question you might be asking yourselfinvolvesprintin () argument data types: how is it possible for the same print in () method to be called wich different types of argument data? The answer: because there are several print in () methods in the printStrean class. Ac runtime, the JVM knows which printin() method to call by examining the number of method-, indicates standard output redirection. Whenever you want to redirect the standard ourput device from the screen to a file or printer, specify that symbol followed by the file or printer name on the command line, For example, redirect Print’s ourput to a Windows printer by issuing the following, command line: Java Print > pen. ‘The Prints tream class provides a printin() method, which takes no arguments. ‘That method ourputs a single new-line character. Behind the scenes, the various printin() methods call their print () method counterparts followed by the rno-argument erintia() method. A close look at the documentation for the no- argument print1n() method shows the newline character being obtained from a system property called 1ine.separatoz. That system property’s value is not necessarily the same as \n. To seek true platform independence, do not hard-code \n in your print () of peintin () arguments (In this course, the \n literal i often specified in source code.) For example: // the following is platform-dependent because of the \n Uf character System.ovt.print (“ABC\ADEE") ; // The following method calle are plat forn-independent System.out.printin ("ARC"); System.out.print ("DEF"); UNIT3 |57 Bascinpuvoutput stream Oum Malik, D $, Java Programming: From Problem Analysis to Pregram Design, ‘Using Dialog boxes for Input/Output’ p. 135-142,

Potrebbero piacerti anche

  • WUC103 Unit2-3
    WUC103 Unit2-3
    Documento16 pagine
    WUC103 Unit2-3
    api-26781128
    Nessuna valutazione finora
  • WUC103 Unit2-1
    WUC103 Unit2-1
    Documento24 pagine
    WUC103 Unit2-1
    api-26781128
    Nessuna valutazione finora
  • WLA105 Unit4-1-2
    WLA105 Unit4-1-2
    Documento24 pagine
    WLA105 Unit4-1-2
    api-26781128
    Nessuna valutazione finora
  • WLA105 Unit5-1-2
    WLA105 Unit5-1-2
    Documento22 pagine
    WLA105 Unit5-1-2
    api-26781128
    Nessuna valutazione finora
  • WUC103 Unit2-2
    WUC103 Unit2-2
    Documento10 pagine
    WUC103 Unit2-2
    api-26781128
    Nessuna valutazione finora
  • WUC103 Unit2-4
    WUC103 Unit2-4
    Documento10 pagine
    WUC103 Unit2-4
    api-26781128
    Nessuna valutazione finora
  • WLA105 Unit5-3
    WLA105 Unit5-3
    Documento18 pagine
    WLA105 Unit5-3
    api-26781128
    Nessuna valutazione finora
  • WLA105 Unit4-3
    WLA105 Unit4-3
    Documento18 pagine
    WLA105 Unit4-3
    api-26781128
    Nessuna valutazione finora
  • WLA105 Unit2-1
    WLA105 Unit2-1
    Documento20 pagine
    WLA105 Unit2-1
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit5-5
    TCC102 Unit5-5
    Documento12 pagine
    TCC102 Unit5-5
    api-26781128
    Nessuna valutazione finora
  • WLA105 Unit2-3
    WLA105 Unit2-3
    Documento10 pagine
    WLA105 Unit2-3
    api-26781128
    Nessuna valutazione finora
  • WLA105 Unit2-4
    WLA105 Unit2-4
    Documento24 pagine
    WLA105 Unit2-4
    api-26781128
    Nessuna valutazione finora
  • WLA105 Unit2-2
    WLA105 Unit2-2
    Documento6 pagine
    WLA105 Unit2-2
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit5-2
    TCC102 Unit5-2
    Documento20 pagine
    TCC102 Unit5-2
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit4-1
    TCC102 Unit4-1
    Documento14 pagine
    TCC102 Unit4-1
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit5-3n4
    TCC102 Unit5-3n4
    Documento14 pagine
    TCC102 Unit5-3n4
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit4-5
    TCC102 Unit4-5
    Documento22 pagine
    TCC102 Unit4-5
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit4-4
    TCC102 Unit4-4
    Documento14 pagine
    TCC102 Unit4-4
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit3 2
    TCC102 Unit3 2
    Documento20 pagine
    TCC102 Unit3 2
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit5-1
    TCC102 Unit5-1
    Documento22 pagine
    TCC102 Unit5-1
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit4-3
    TCC102 Unit4-3
    Documento12 pagine
    TCC102 Unit4-3
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit3 Summary
    TCC102 Unit3 Summary
    Documento16 pagine
    TCC102 Unit3 Summary
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit4-2
    TCC102 Unit4-2
    Documento26 pagine
    TCC102 Unit4-2
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit3 3
    TCC102 Unit3 3
    Documento14 pagine
    TCC102 Unit3 3
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit2 5
    TCC102 Unit2 5
    Documento13 pagine
    TCC102 Unit2 5
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit2 4
    TCC102 Unit2 4
    Documento24 pagine
    TCC102 Unit2 4
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit2 Summary
    TCC102 Unit2 Summary
    Documento25 pagine
    TCC102 Unit2 Summary
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit3 1
    TCC102 Unit3 1
    Documento14 pagine
    TCC102 Unit3 1
    api-26781128
    Nessuna valutazione finora
  • TCC102 Unit2 3
    TCC102 Unit2 3
    Documento12 pagine
    TCC102 Unit2 3
    api-26781128
    Nessuna valutazione finora