0% found this document useful (0 votes)
9 views

3-COE312 - Lecture Java IO

The document covers Java I/O (Input and Output) concepts, including error handling through exceptions, the use of streams for efficient data processing, and practical examples of reading from and writing to files. It explains the importance of buffering in I/O operations to ensure smooth data flow and introduces classes like BufferedOutputStream and DataOutputStream for enhanced functionality. Additionally, it highlights the differences between streams and files in Java, emphasizing the efficiency of using data streams for numerical data.

Uploaded by

toshionoeiyu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

3-COE312 - Lecture Java IO

The document covers Java I/O (Input and Output) concepts, including error handling through exceptions, the use of streams for efficient data processing, and practical examples of reading from and writing to files. It explains the importance of buffering in I/O operations to ensure smooth data flow and introduces classes like BufferedOutputStream and DataOutputStream for enhanced functionality. Additionally, it highlights the differences between streams and files in Java, emphasizing the efficiency of using data streams for numerical data.

Uploaded by

toshionoeiyu
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

1

Java I/O
COE312
Omar Arif
Slides adapted from Dr Imran Zualkernan slides.
2

 When executing Java code, different errors can


occur:
 When an error occurs, Java will normally stop and
Error generate an error message.

Handling  The technical term for this is: Java will throw
an exception (throw an error).
3

 The try statement allows you to define a block of code to


be tested for errors while it is being executed.
 The catch statement allows you to define a block of code
to be executed, if an error occurs in the try block.
 The finally statement is executed regardless of whether
an exception was thrown or not
 The try and catch keywords come in pairs:
Exception
Handling try {
// Block of code to try
}catch(Exception e) {
// Block of code to handle errors
}finally {
// code that is guaranteed to execute
}
4

 How to interact with external sources


 How to read and write “files”?
 How to send data back and forth between
programs
Java I/O  How to process the input and produce the output.

 We will follow the tutorial given in:


 https://www.javatpoint.com/java-io
5

 Java I/O (Input and Output) is used to process


the input and produce the output.
 The java.io package contains all the classes
required for input and output operations.
Java I/O  We can perform file handling in Java by Java I/O
API.
6

 Java uses the concept of a stream to make I/O


operation fast.
 A stream is a sequence of data.
 In Java, a stream is composed of bytes.
 It is called a stream because it is like a stream of
water that continues to flow.

Streams  In Java, three streams are created for us


automatically. All these streams are attached to
the console.
 1) System.out: standard output stream
 2) System.in: standard input stream
 3) System.err: standard error stream
7

 Java application uses an output stream to write

Input and data to a destination; it may be a file, an array,


peripheral device or socket.
Output  Java application uses an input stream to read data

streams from a source; it may be a file, an array,


peripheral device or socket.
8

Input and Output Streams


9

OutputStream Class Hierarchy


10

Method Description

1) public void write(int)throws is used to write a byte to the

Methods of IOException current output stream.

OutputStre
2) public void write(byte[])throws is used to write an array of
IOException byte to the current output
stream.
am 3) public void flush()throws flushes the current output
IOException stream.

4) public void close()throws is used to close the current


IOException output stream.

Flush means actually do the write()


NOW as opposed to doing the write()
sometime in the future.
12

import java.io.FileOutputStream;

public class Main {

Example public static void main(String args[]){


try{

writing a FileOutputStream fout=new

FileOutputStream(”testout.txt");
single fout.write(65); // Write ‘A’

character fout.close();
System.out.println("success...");

}catch(Exception e){
System.out.println(e);
}
}
}

This will write ‘A’ to the file called testout.txt.


13

File is located in
the Eclipse project
folder (FileOutput)

Output is a
file called
testout.txt
14

import java.io.FileOutputStream;

public class Main {


public static void main(String args[]) {
try {

FileOutputStream fout = new FileOutputStream("testout.txt");

Example – String s = "Welcome to COE312";

Writing a array
byte [] b = s.getBytes();// converting String into byte

String to a
file fout.write(b);
fout.close();

System.out.println("success...");
} catch (Exception e) {
System.out.println(e);
}
}
}
15

Output to a
String
16

InputStream
17

Method Description

1) public abstract int reads the next


read()throws IOException byte of data from
the input stream.
It returns -1 at
the end of the Methods of
InputStrea
file.
2) public int returns an
available()throws
IOException
estimate of the
number of bytes
that can be read
m
from the current
input stream.

3) public void is used to close


close()throws IOException the current input
stream.
18
Method Description

int available() It is used to return the estimated


number of bytes that can be read
from the input stream.

int read() It is used to read the byte of data


from the input stream.

int read(byte[] b) It is used to read up

FileInputStre
to b.length bytes of data from the
input stream.

am
int read(byte[] b, int off, int It is used to read up to len bytes of
len) data from the input stream.

long skip(long x) It is used to skip over and discards x


bytes of data from the input stream.

FileDescriptor getFD() It is used to return the FileDescriptor


object.

void close() It is used to closes the stream.


import java.io.FileInputStream; 19

public class Main {


public static void main(String args[]) {
try {
FileInputStream fin = new

Example – FileInputStream(”input.txt");
Note we read an int.
Reading a int i = fin.read();

single System.out.print((char) i);


character Note we convert int to char.

fin.close();

} catch (Exception e) {
System.out.println(e);
}
}
}
20

 Java reads a single byte as an int (4 bytes)*.


Jocker  However, it throws away the top three bytes.
moment  Therefore, we need to convert the read int into
a char or byte to read a single character or
byte.
 Bottom line: To read a byte or characters, read
int using read() and coerce it to byte or char.
*This design choice was made because the method returns -1 to
indicate end of stream. If it returned a byte, then -1 could not be
returned to indicate a lack of input because -1 is a valid byte
import java.io.FileInputStream; 21

public class Main {


public static void main(String args[]) {
try {
FileInputStream fin = new

Example – FileInputStream("testout.txt");
Note: EOF is the same as -1
Reading int i = 0;

many while ((i = fin.read()) != -1) {

characters System.out.print((char) i);

fin.close();
} catch (Exception e) {
System.out.println(e);
}
}}
22

 One problem when writing and reading data is that data


does not necessarily arive in a “smooth” manner and may
come in bursts.
 In such cases, we would like to use a buffer that “fills up”
while the bytes are sent or received to have ”smooth” data
flow.
 Doing this will also not overwhelm the reciever of data

Buffered because they will not get “bursts” of data.

Streams

Sender

Buffer Receiver
23

 Can we add a Buffer to the FileOutputStream so

Problem when we send data, it goes smoothely to


whomsoever is receiving it?
24

Adding a
Buffer to the
FileOutputSt
ream
25

 BufferedOutputStream does the buffering and


asks FileOutputStream to write to File?

write

Solution BufferedOutputStrea FileOutputStrea


m m

does the buffering writes to file


 BufferedOutputStream class is used for 26

buffering an output stream.

 It internally uses buffer to store data.


 It adds more efficiency than to write data directly
into a stream.

 So, it makes the performance better.

Constructor Description

BufferedOut BufferedOutputStream(Out It creates the new buffered


putStream os) output stream which is used

putStream for writing the data to the


specified output stream.

BufferedOutputStream(Out It creates the new buffered


putStream os, int size) output stream which is used
for writing the data to the
specified output stream with a
specified buffer size.
27

BufferedOutputStrea FileOutputStrea
m m

import java.io.*;

public class Main {


public static void main(String args[]) throws Exception {

Example FileOutputStream fout = new

FileOutputStream("testout.txt");

BufferedOutputStream bout = new

BufferedOutputStream(fout);

String s = "Welcome to COE312 from Buffering.";

byte b[] = s.getBytes();


bout.write(b);

bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
28

BufferedOutputStream simply adds buffering to every write().

Wrapping bout.write()

functionality BufferedOutputStream
around (add buffering)
write()
existing one
FileOutputStream
(writes to file)
29

import java.io.*;

public class Main {


public static void main(String args[]) {
try {
FileInputStream fin = new FileInputStream(”input.txt");

Example – BufferedInputStream bin = new BufferedInputStream(fin);

Using int i;
while ((i = bin.read()) != -1) {
System.out.print((char) i);
InputBuffer }

bin.close();
fin.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
30

BufferedInputStream simply adds buffering to every read().

New Idea – bout.read()

Wrapping
functionality BufferedInputStream
(add buffering)
around existing read()
one
FileInputStream
(read data from file)
31

 We “wrap” a class (e.g., BufferedOutputStream)


to add new functionality to another class (e.g.,
FileOutputStream).

Wrapping FileOutputStream
Model

BufferedOutputStream
32

 DataOutputStream class allows an application


to write primitive Java data types to the output
stream in a machine-independent way.
 Java application generally uses the
DataOutputStre
DataOutputStream to write data that can later
am be read by a DataInputStream.
 Example would include getting data from a
drone or a weather station, etc.
33

Primitive
data types
in Java

https://www.binaryconvert.com/
result_float.html?
decimal=0510460490520490530
57
34

 DataOutputStream writes the ‘binary image’ of


the data as is.
 For example, the 32 bits representing an IEEE
floating point are written as a memory image.
DataOutputStre
 Consequently, output of DataOutputStream is
am not readable by humans.
 However, another program using
DataInputStream can read the output correctly.
35
Method Description

int size() It is used to return the number of bytes written to


the data output stream.

void write(int b) It is used to write the specified byte to the


underlying output stream.

void write(byte[] b, int off, It is used to write len bytes of data to the output
int len) stream.

void writeBoolean(boolean It is used to write Boolean to the output stream as


v) a 1-byte value.

void writeChar(int v) It is used to write char to the output stream as a 2-


byte value.

DataOutputStr void writeChars(String s) It is used to write string to the output stream as a


sequence of characters.

eam void writeByte(int v) It is used to write a byte to the output stream as a


1-byte value.

void writeBytes(String s) It is used to write string to the output stream as a


sequence of bytes.

void writeInt(int v) It is used to write an int to the output stream

void writeShort(int v) It is used to write a short to the output stream.

void writeShort(int v) It is used to write a short to the output stream.

void writeLong(long v) It is used to write a long to the output stream.

void writeUTF(String str) It is used to write a string to the output stream


using UTF-8 encoding in portable manner.

void flush() It is used to flushes the data output stream.


36
import java.io.*;

public class Main {


public static void main(String[] args) throws IOException {

FileOutputStream file = new

FileOutputStream(”data.txt");

DataOutputStream data = new DataOutputStream(file);

data.writeFloat((float)3.14159);;

Example data.flush();

data.close();

System.out.println("Succcess...");
}
}

not readable by humans.


37

Method Description

int read(byte[] b) It is used to read the number of bytes from the


input stream.

int read(byte[] b, int off, int len) It is used to read len bytes of data from the
input stream.

int readInt() It is used to read input bytes and return an int


value.

byte readByte() It is used to read and return the one input


byte.

char readChar() It is used to read two input bytes and returns a

DataInputStre
char value.

double readDouble() It is used to read eight input bytes and returns


a double value.

am boolean readBoolean() It is used to read one input byte and return


true if byte is non zero, false if byte is zero.

int skipBytes(int x) It is used to skip over x bytes of data from the


input stream.

String readUTF() It is used to read a string that has been


encoded using the UTF-8 format.

void readFully(byte[] b) It is used to read bytes from the input stream


and store them into the buffer array.

void readFully(byte[] b, int off, int len) It is used to read len bytes from the input
stream.
38

import java.io.*;

public class Driver {


public static void main(String[] args) throws IOException {

InputStream input = new FileInputStream("data.txt");


DataInputStream inst = new DataInputStream(input);
Example float f = inst.readFloat();
System.out.println(f);
}
}

The value of pi read and printed


correctly.
3.14159 39
writeFloat()

DataOutputStream DataoutputStream writes

FileOutputStream

01000000 Data is stored in


Data 01001001
00001111
non- human
readable binary
Streams 11010000 format.

FileInputStream

DataInputStream DataInputStream reads

readFloat()
3.14159
40

 Please note that we could have stored 3.14159 as


a String ”3.14159” and this would take 7 bytes to
store.
Why do  Using Float we only 4 bytes to store 3.14159.
this?  So in general, when dealing with numbers, we
should use data input and output streams as it is
more elegant and more efficient.
41

 Files are not the same as streams in Java.


 Files can be manipulated independently of

File Object streams.


 Streams can be tied to files for reading and writing
files.
42

import java.io.File;
import java.io.IOException;

public class Driver {


public static void main(String[] args) {

try {
File file = new File("output.txt");
Example if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}

}
}
43

 There are many other Java I/O classes.

Many other  Readers and Writers read and write

classes in  Scanner is used to read input from console

Java IO  Console we are already familiar with (System.in


and System.out)
44

 Java I/O is done through input and output streams

Summary  A variety of classes implementing various input


and output functionalities has been provided.

You might also like