-
Character stream for ...
- - commercial code
- - easier to internationalize and maintain
- - more convenient to operate directly on characters
-
Byte Stream for ...
- - simple utility program
- - raw keyboard input
-
Writing to Console Input we use
System.out
-
Reading Console Input from keyboard we use
System.in
-
What methods can be used using System.out ?
- 1) Because System.out is an instance of PrintStream we automatically have access to the methods defined by PrintStream.
- write(int b)
- write(byte[ ] b)
- write(byte[ ] b, int off, int len
2) Because PrintStream is an output stream derived from OutputStream we automatically have access to the methods of OutputStream.- print(char c)
- println()
-
What methods can be used using System.in ?
- Because System.in is an instance of InputStream, we automatically have access to the methods defined by InputStream
- read()
- read(byte[ ] b)
- read(byte[ ] b, int off, int len)
-
How many input methods defined in InputStream
InputStream defines only one input method read( ) having three versions
-
Three versions of read( ) in InputStream:
- 1) int read( ) throws IOException
- - reads single char from keyboard
- - returns –1 when the end of the stream is encountered
- 2) int read(byte data[ ]) throws IOException
- - read characters from keyboard and put into data[ ]
- - returns the number of bytes read
- - returns –1 when the end of the stream is encountered
- 3) int read(byte data[ ], int start, int max) throws IOException
- - reads input into data[ ] beginning at location "start" up to "max" bytes
- - returns the number of bytes read
- - returns –1 when the end of the stream is encountered
-
Reading Console Input from keyboard example:
- main(String[ ] args) throws IOException {
- byte b[] = new byte[10];
- byte c[] = new byte[10];
- System.out.println("Please enter text:"); // "Anatoliy"
-
- System.in.read(b, 5, 2); // " An "
- System.in.read(b, 0, 2); // "at An "
- System.in.read(c); // "oliy "
- }
-
Using System.in any I/O exceptions that might be generated are simply thrown out ...
of main( )
- main(String[ ] args) throws IOException {
- ...
- }
-
Writing Console Output is most easily accomplished with:
- System.out
- print( )
and println( )
-
print( ) and println( ) methods are defined by the class:
OutputStream.FilterStream.PrintStream
-
System.out is an instance of ...
- OutputStream . FilterOutputStream . PrintStream
- you automatically have access to the methods of PrintStream (print( ) and println( )) and OutputStream (Three versions of write( ))
-
Writing Console Output example:
- public static void main(String[ ] args) {
- int b;
- b = 'X';
- System.out.write(b);
- System.out.write('n');
- System.out.print(b);
- System.out.println('n');
- }
-
Three versions of write() of OutputStream
- 1) void write(int b)
- - Writes the single specified byte to this output stream
- 2) void write(byte[ ] b)
- - Writes b.length bytes from the specified byte array
- 3) void write(byte[ ] b, int off, int len)
- - Writes "len" bytes from the specified byte array starting at offset "off"
-
Reading Files Using Byte Streams we have to ...
create a byte stream linked to a file using InputStream.FileInputStream
-
Steps to Read Files Using Byte Streams
- 1) Declare var "fin" of type "FileInputStream" initializing to null:
- FileInputStream fin = null;
- 2) Make sure that file has been specified:
- if(args.length != 1){
- System.out.println("File is not specified");
- return;
- }
- 3) Open file:
- To open a file for input, create a FileInputStream object sending name of the file with args[0]
- fin = new FileInputStream(args[0]);
- throws FileNotFoundException
- 4)
Read the opened file- do{
- int i = fin.read();
- if(i != -1)
- System.out.print((char)i);
- } while(i != -1);
// end of filethrows IOException- 5)
Close the file only if it was successfully opened - if(fin != null) fin.close();throws IOException exc
-
Open file
- To open a file for input, create a FileInputStream object sending name of the file with args[0]
- fin = new FileInputStream(args[0]);
throws FileNotFoundException
-
Make sure that file has been specified
- if(args.length != 1)
- System.out.println("File is not specified");
- return;
- }
-
Read file
- do{
- int i = fin.read();
- if(i != -1)
- System.out.print((char)i);
- } while(i != -1); // end of file
- throws IOException
-
Close file
- Close the file only if it was successfully opened
- if(fin != null) fin.close();
- throws IOException exc
-
No matter how the "try" block terminates (even w non-I/O-related exception), the file will be closed using:
- Finally Block:
- finally{
- try{
- if(fin != null) fin.close();
- } catch(IOException ecx){
- System.out.println("Error closing file");
- }
- }
-
Automatically Closing a File:
1 - another name
2 - It prevents ...
3 - Description
4 - Example
5 - How file is closed ?
- 1 - another name try-with-resources block
- 2 - It prevents situations in which a file (or other resource) is inadvertently not released after it is no longer needed.
- 3 - Description - Statement that declares and initializes a resource (open file), such as a file is inside the "try" statement.
- 4 - Example:
- try(FileInputStream fin = new FileInputStream(args[0])){ // Open File
- do{
- i = fin.read(); // Read File
- ...
- }
- } catch(FileNotFoundException exc){
- System.out.println("File Not Found Exception");
- } catch(IOException exc){
- System.out.println("IOException: " + exc);
- }
- 5 - When the try block ends, the resource is automatically released (file is closed)
-
How try-with-resources can be used when working with streams
- 1) There are 2 interfaces:
- java.lang.AutoCloseable
- java.io.Closeable
- 2) AutoCloseable is inherited by the (child of) Closeable interface
- 3) Both interfaces are implemented by the stream classes, including FileInputStream and FileOutputStream
- 4) Thus, try-with-resources can be used when working with streams, including file streams.
-
Another advantage of using try-with-resources statement
- - Exception inside the try block may lead to another exception that occurs when the resource is closed in a finally clause. The original exception is lost, being preempted by the second exception.
- - With a try-with-resources statement, the second exception is not lost, it is "suppressed". It is added to the list of suppressed exceptions associated with the first exception.
- - To obtain list of suppressed exceptions we can use getSuppressed( ) method defined by Throwable
-
getSuppressed( )
Method defined by Throwable which can be used to obtain list of suppressed exceptions.
-
Reasons to know traditional approach to close the file (3).
- 1) There is legacy code that still relies on the traditional approach.
- 2) You might need to work in an environment that predates JDK 7
- 3) There may be cases in which explicitly closing a resource is more appropriate
-
Writing Files Using Byte Streams we have to ...
- create a byte stream linked to a file using OutputStream.FileOutputStream
- Example:
- public static void main(String[] args) {
- int i = 8;
- boolean a = true;
-
// check if file is specified- if(args.length != 1){
- System.out.println("File is not specidied");
- return;
- }
-
// open file using try-with-resources statement-
// a = true, do not flash file, write to the end- try(FileOutputStream fout = new FileOutputStream(args[0], a)){
-
// write to the file- fout.write(i);
- } catch(IOException exc){
System.out.println("I/O Error: " + exc);- }
- }
-
Reading Binary Data
- - To read binary values of the Java primitive types ints, doubles, or shorts we will use DataInputStream
- InputStream ->
- FilterInputStream ->
- DataInputStream ->
implements interface ->- DataInput ->
defines methods:- readBoolean()
- - Byte()
- - Char()
- - Double()
- - Float()
- - Int()
- - Long()
- - Short()
-
Writing Binary Data
- - To write binary values of the Java primitive types ints, doubles, or shorts we will use DataOutputStream
- OutputStream ->
- FilterOutputStream ->
- DataOutputStream ->
implements interface ->- DataOutput ->
defines methods:- writeBoolean()
- - Byte()
- - Char()
- - Double()
- - Float()
- - Int()
- - Long()
- - Short()
-
Example of Writing Binary Data
- try(DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("testData"))){
- dataOut.writeInt(i);
- dataOut.writeDouble(d);
- dataOut.writeBoolean(b);
- } catch(IOException exc){
- System.out.println("I/O Error: " + exc);
- }
-
Example of Reading Binary Data
- try(DataInputStream dataIn = new DataInputStream(new FileInputStream("testData"))){
- ii = dataIn.readInt() + 5;
- dd = dataIn.readDouble() + 5;
- bb = dataIn.readBoolean();
- System.out.print(ii + " " + dd + " " + bb);
- } catch(IOException exc){
- System.out.println("I/O Error: " + exc);
- }
|
|