SlideShare a Scribd company logo
2
Most read
3
Most read
5
Most read
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
١
I/O Streams
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. A stream is a way
of sequentially accessing a file. It's called a stream because it is like a stream of water
that continues to flow. There are two kinds of Streams:
OutputStream
Java application uses an output stream to write data to a destination, it may be a file, an
array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file, an
array, peripheral device or socket.
‫خروجي‬ ‫استريمهاي‬ ‫يكي‬ :‫داريم‬ ‫استريم‬ ‫نو‬ ‫دو‬ .‫آب‬ ‫جريان‬ ‫مثل‬ .‫شود‬ ‫مي‬ ‫ارائه‬ ‫بايت‬ ‫بصورت‬ ‫كه‬ ‫باشد‬ ‫مي‬ ‫ديتا‬ ‫از‬ ‫اي‬ ‫رشته‬ ‫يك‬ ‫استريم‬
‫استريمهاي‬ ‫ديگري‬ ‫و‬.‫ورودي‬
Stream Hierarchy:
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
٢
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. A byte stream
access the file byte by byte. A byte stream is suitable for any kind of file, however not
quite appropriate for text files.There are many classes related to byte streams but the
most frequently used classes are, FileInputStream and FileOutputStream.
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream would create
a file, if it doesn't already exist, before opening it for output.
Method Description
protected void finalize() It is sued to clean up the connection with the file output stream.
Ensures that the close method of this file output stream is called when
there are no more references to this stream. Throws an IOException.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file output
stream.
void write(byte[] ary, int off,
int len)
It is used to write len bytes from the byte array starting at offset off to
the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file output
stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
void close() It is used to closes the file output stream.
Example:
try{
FileOutputStream fout=new FileOutputStream("D:testout.txt");
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}
catch(Exception e){System.out.println(e);}
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
٣
FileInputStream Class
FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented
data (streams of raw bytes) such as image data, audio, video etc. You can also read
character-stream data. But, for reading streams of characters, it is recommended to use
FileReader class.
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 to b.length bytes of data from the input
stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of 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.
FileChannel getChannel() It is used to return the unique FileChannel object associated
with the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize() It is used to ensure that the close method is call when there is
no more reference to the file input stream.
void close() It is used to closes the stream.
Example: Read a file with FileInputStream
try{
FileInputStream fin=new FileInputStream("D:testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
۴
Example: Create a file & read it again
try {
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x = 0; x < bWrite.length ; x++) {
os.write( bWrite[x] ); // writes the bytes
}
os.close();
InputStream ins = new FileInputStream("test.txt");
int size = ins.available();
for(int i = 0; i < size; i++) {
System.out.print((char)ins.read() + " ");
}
ins.close();
}catch(IOException e) {
System.out.print("Exception");
}
Example: CopyFile
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close(); }
if (out != null) {
out.close();}
} } }
Character Streams
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
۵
Java Character streams are used to perform input and output for 16-bit unicode. A character
stream will read a file character by character. Character streams are appropriate for text files.
A character stream needs to be given the file's encoding in order to work properly. Though there
are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
Example:
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
BufferedOutputStream
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
۶
Java BufferedOutputStream class is used for 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 fast.
Example:
FileOutputStream fileOut=new FileOutputStream("D:testout.txt");
BufferedOutputStream bufferOut=new BufferedOutputStream(fileOut);
String s="Welcome to javaTpoint.";
byte b[]=s.getBytes();
bufferOut.write(b);
bufferOut.flush();
bufferOut.close();
fileOut.close();
System.out.println("success");
BufferedInputStream
BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.
Example:
try{
FileInputStream fileIn=new FileInputStream("D:testout.txt");
BufferedInputStream bufferIn=new BufferedInputStream(fileIn);
int i;
while((i= bufferIn.read())!=-1){
System.out.print((char)i);
}
String str;
while ((str= bufferIn.readLine())!=null) { // for reading a line
System.out.println(str);
}
bufferIn.close();
fileIn.close();
}catch(Exception e){System.out.println(e);}
Properties Class
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
٧
Properties is a subclass of Hashtable. It is used to maintain lists of values in which the
key is a String and the value is also a String. Normally, Java properties file is used to store
project configuration data or settings.
Method Description
public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key,String
value)
sets the property in the properties object.
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String
comment)
writes the properties in the OutputStream object.
storeToXML(OutputStream os, String
comment)
writers the properties in the writer object for
generating xml document.
public void storeToXML(Writer w, String
comment, String encoding)
writers the properties in the writer object for
generating xml document with specified
encoding.
Example
String filePath = "E: databaseProperties.properties";
Properties properties = new Properties();
FileInputStream fileIn = new FileInputStream(filePath);
properties.load(fileIn);
fileIn.close();
String mysqlDriver = properties.getProperty("mysql.jdbc.driverClassName");
PrintStream:
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
٨
The PrintStream class provides methods to write formatted data to another output stream. It
can format primitive types like int, long etc. formatted as text, rather than as their byte values.
That is why it is called a PrintStream, because it formats the primitive values as text - like
they would look when printed to the screen (or printed to paper).
The PrintStream class automatically flushes the data so there is no need to call flush() method.
Moreover, its methods don't throw IOException.
‫مثل‬ ‫هايی‬ ‫متغيره‬ ‫مثﻼ‬ .‫نويسد‬ ‫می‬ ‫ديگر‬ ‫خروجی‬ ‫استريم‬ ‫يک‬ ‫به‬ ‫را‬ ‫است‬ ‫خاصی‬ ‫فرمت‬ ‫دارای‬ ‫که‬ ‫را‬ ‫اطﻼعاتی‬ ‫متد‬ ‫اين‬Int‫يا‬Long
.‫کرد‬ ‫کپی‬ ‫ديگر‬ ‫استريم‬ ‫يک‬ ‫در‬ ،‫بکنيم‬ ‫بايت‬ ‫به‬ ‫تبديل‬ ‫را‬ ‫آنها‬ ‫ابتدا‬ ‫باشيم‬ ‫مجبور‬ ‫اينکه‬ ‫بدون‬ ‫توان‬ ‫می‬ ‫را‬
Example:
import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:testout.txt ");
PrintStream pout=new PrintStream(fout);
pout.println(true);
pout.println(2016);
pout.println((float) 123.456);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
System.out.println("Success?");
}
}
File Lock:
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
٩
In java we have the ability to lock a region of a file or the entire file.The file locking mechanism is
handled by the operating system.There are two kinds of file locking:
Exclusive: Only one program can hold an exclusive lock on a region of a file.
shared: Multiple programs can hold shared locks on the same region of a file.
We acquire a lock on a file by using the lock() or tryLock() method of the FileChannel object. If you
use these methods without an argument, they lock the entire file.
isShared(): The isShared() method of the FileLock object returns true if the lock is shared;
otherwise, it returns false.
Example:
public class Main {
public static void main(String[] args) throws Exception {
RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
FileChannel fileChannel = raf.getChannel();
FileLock lock = null;
try {
lock = fileChannel.lock(); // Lock all file
lock = fileChannel.lock(0, 10, false); // Get an exclusive lock first 10 byte
lock = fileChannel.tryLock(11, 100, true); // tries to lock first 10 byte on first 10 byte
if (lock == null) { // Could not get the lock
} else { // Got the lock }
} catch (IOException e) {
// Handle the exception
} finally {
if (lock != null) {
try {
lock.release();
} catch (IOException e) {
// Handle the exception
}
}
}
}
}
Serializable:
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
١
Serialization in java is a mechanism of writing an object as a sequence of bytes that includes the
object's data as well as information about the object's type and the types of data stored in the object.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies. The reverse operation of serialization is
called deserialization.
After a serialized object has been written into a file, it can be read from the file and deserialized that
is, the type information and bytes that represent the object and its data can be used to recreate the
object in memory.
Notice: that for a class to be serialized successfully, two conditions must be met:
 The class must implement the java.io.Serializable interface.
 All of the fields in the class must be serializable. If a field is not serializable, it must be
marked transient.
Example:
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}
Read and Write Java Objects:
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
١
In order to write objects into a file, objects must be converted into byte-stream using
ObjectOutputStream. It is mandatory that the concerned class implements Serializable
interface.
ObjectInputStream can be used to de-serialize and read java objects that have been serialized
and written using ObjectOutputStream.
Example:
public static void main(String[] args) {
Person p1 = new Person("John", 30, "Male");
Person p2 = new Person("Rachel", 25, "Female");
try {
FileOutputStream f = new FileOutputStream(new File("myObjects.txt"));
ObjectOutputStream o = new ObjectOutputStream(f);
// Write objects to file
o.writeObject(p1);
o.writeObject(p2);
o.close();
f.close();
FileInputStream fi = new FileInputStream(new File("myObjects.txt"));
ObjectInputStream oi = new ObjectInputStream(fi);
// Read objects
Person pr1 = (Person) oi.readObject();
Person pr2 = (Person) oi.readObject();
System.out.println(pr1.toString());
System.out.println(pr2.toString());
oi.close();
fi.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter class:
PrintWriter class is the implementation of Writer class. It is used to print the formatted representation
of objects to the text-output stream.
Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid
١
public class PrintWriterExample {
public static void main(String[] args) throws Exception {
//Data to write on Console using PrintWriter
PrintWriter writer = new PrintWriter(System.out);
writer.write("Javatpoint provides tutorials of all technology.");
writer.flush();
writer.close();
//Data to write in File using PrintWriter
PrintWriter writer1 =null;
writer1 = new PrintWriter(new File("D:testout.txt"));
writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");
writer1.flush();
writer1.close();
}
}

More Related Content

PPT
Java Streams
PPTX
Classes, objects in JAVA
PPTX
MULTI THREADING IN JAVA
PPTX
Control structures in java
PDF
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
PPT
Graphs In Data Structure
PPT
Exception Handling in JAVA
PPTX
Event Handling in java
Java Streams
Classes, objects in JAVA
MULTI THREADING IN JAVA
Control structures in java
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
Graphs In Data Structure
Exception Handling in JAVA
Event Handling in java

What's hot (20)

PPTX
Vectors in Java
PPTX
L21 io streams
PPSX
Data Types & Variables in JAVA
PDF
Java threads
PPTX
I/O Streams
PPTX
Strings in Java
PPTX
Applets in java
PPT
Java And Multithreading
PPT
Applet life cycle
PPT
9. Input Output in java
PPTX
Arrays in Java
PPT
Java Networking
PPT
Input output streams
PPS
String and string buffer
PPTX
Method overloading
PPTX
Super keyword in java
PPTX
Event handling
PDF
Java IO
PPT
Thread model in java
Vectors in Java
L21 io streams
Data Types & Variables in JAVA
Java threads
I/O Streams
Strings in Java
Applets in java
Java And Multithreading
Applet life cycle
9. Input Output in java
Arrays in Java
Java Networking
Input output streams
String and string buffer
Method overloading
Super keyword in java
Event handling
Java IO
Thread model in java
Ad

Similar to Java I/o streams (20)

PDF
Java IO Stream, the introduction to Streams
PPTX
Input output files in java
PPT
Jedi Slides Intro2 Chapter12 Advanced Io Streams
PDF
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
PPTX
Java I/O
PPTX
Input/Output Exploring java.io
PDF
File Handling in Java.pdf
PDF
What is java input and output stream?
PDF
What is java input and output stream?
PPT
Itp 120 Chapt 19 2009 Binary Input & Output
PPTX
File Input and output.pptx
PPTX
Understanding java streams
PPTX
IO Programming.pptx all informatiyon ppt
PPT
Chapter 12 - File Input and Output
PPT
Java căn bản - Chapter12
PPTX
File Handling.pptx
PPSX
Files in c++
PDF
Filesinc 130512002619-phpapp01
PPTX
Chapter 10.3
Java IO Stream, the introduction to Streams
Input output files in java
Jedi Slides Intro2 Chapter12 Advanced Io Streams
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
Java I/O
Input/Output Exploring java.io
File Handling in Java.pdf
What is java input and output stream?
What is java input and output stream?
Itp 120 Chapt 19 2009 Binary Input & Output
File Input and output.pptx
Understanding java streams
IO Programming.pptx all informatiyon ppt
Chapter 12 - File Input and Output
Java căn bản - Chapter12
File Handling.pptx
Files in c++
Filesinc 130512002619-phpapp01
Chapter 10.3
Ad

More from Hamid Ghorbani (16)

PDF
Spring aop
PDF
Spring boot jpa
PDF
Spring mvc
PDF
Payment Tokenization
PDF
Reactjs Basics
PDF
Rest web service
PDF
Java inheritance
PDF
Java Threads
PDF
Java Reflection
PDF
Java Generics
PDF
Java collections
PDF
Java programming basics
PDF
IBM Integeration Bus(IIB) Fundamentals
PDF
ESB Overview
PDF
Spring security configuration
PDF
SOA & ESB in banking systems(Persian language)
Spring aop
Spring boot jpa
Spring mvc
Payment Tokenization
Reactjs Basics
Rest web service
Java inheritance
Java Threads
Java Reflection
Java Generics
Java collections
Java programming basics
IBM Integeration Bus(IIB) Fundamentals
ESB Overview
Spring security configuration
SOA & ESB in banking systems(Persian language)

Recently uploaded (20)

PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
System and Network Administraation Chapter 3
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
PPT
JAVA ppt tutorial basics to learn java programming
PDF
Digital Strategies for Manufacturing Companies
PDF
Comprehensive Salesforce Implementation Services.pdf
DOCX
The Five Best AI Cover Tools in 2025.docx
PDF
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
System and Network Administration Chapter 2
PDF
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
AIRLINE PRICE API | FLIGHT API COST |
PDF
Become an Agentblazer Champion Challenge
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
top salesforce developer skills in 2025.pdf
PDF
How to Confidently Manage Project Budgets
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
System and Network Administraation Chapter 3
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
JAVA ppt tutorial basics to learn java programming
Digital Strategies for Manufacturing Companies
Comprehensive Salesforce Implementation Services.pdf
The Five Best AI Cover Tools in 2025.docx
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
PTS Company Brochure 2025 (1).pdf.......
System and Network Administration Chapter 2
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
2025 Textile ERP Trends: SAP, Odoo & Oracle
Upgrade and Innovation Strategies for SAP ERP Customers
AIRLINE PRICE API | FLIGHT API COST |
Become an Agentblazer Champion Challenge
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Which alternative to Crystal Reports is best for small or large businesses.pdf
top salesforce developer skills in 2025.pdf
How to Confidently Manage Project Budgets

Java I/o streams

  • 1. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ١ I/O Streams Stream A stream is a sequence of data.In Java a stream is composed of bytes. A stream is a way of sequentially accessing a file. It's called a stream because it is like a stream of water that continues to flow. There are two kinds of Streams: OutputStream Java application uses an output stream to write data to a destination, it may be a file, an array, peripheral device or socket. InputStream Java application uses an input stream to read data from a source, it may be a file, an array, peripheral device or socket. ‫خروجي‬ ‫استريمهاي‬ ‫يكي‬ :‫داريم‬ ‫استريم‬ ‫نو‬ ‫دو‬ .‫آب‬ ‫جريان‬ ‫مثل‬ .‫شود‬ ‫مي‬ ‫ارائه‬ ‫بايت‬ ‫بصورت‬ ‫كه‬ ‫باشد‬ ‫مي‬ ‫ديتا‬ ‫از‬ ‫اي‬ ‫رشته‬ ‫يك‬ ‫استريم‬ ‫استريمهاي‬ ‫ديگري‬ ‫و‬.‫ورودي‬ Stream Hierarchy:
  • 2. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ٢ Byte Streams Java byte streams are used to perform input and output of 8-bit bytes. A byte stream access the file byte by byte. A byte stream is suitable for any kind of file, however not quite appropriate for text files.There are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. FileOutputStream FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output. Method Description protected void finalize() It is sued to clean up the connection with the file output stream. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException. void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file output stream. void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at offset off to the file output stream. void write(int b) It is used to write the specified byte to the file output stream. FileChannel getChannel() It is used to return the file channel object associated with the file output stream. FileDescriptor getFD() It is used to return the file descriptor associated with the stream. void close() It is used to closes the file output stream. Example: try{ FileOutputStream fout=new FileOutputStream("D:testout.txt"); String s="Welcome to javaTpoint."; byte b[]=s.getBytes();//converting string into byte array fout.write(b); fout.close(); System.out.println("success..."); } catch(Exception e){System.out.println(e);}
  • 3. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ٣ FileInputStream Class FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class. 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 to b.length bytes of data from the input stream. int read(byte[] b, int off, int len) It is used to read up to len bytes of 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. FileChannel getChannel() It is used to return the unique FileChannel object associated with the file input stream. FileDescriptor getFD() It is used to return the FileDescriptor object. protected void finalize() It is used to ensure that the close method is call when there is no more reference to the file input stream. void close() It is used to closes the stream. Example: Read a file with FileInputStream try{ FileInputStream fin=new FileInputStream("D:testout.txt"); int i=0; while((i=fin.read())!=-1){ System.out.print((char)i); } fin.close(); }catch(Exception e){System.out.println(e);}
  • 4. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ۴ Example: Create a file & read it again try { byte bWrite [] = {11,21,3,40,5}; OutputStream os = new FileOutputStream("test.txt"); for(int x = 0; x < bWrite.length ; x++) { os.write( bWrite[x] ); // writes the bytes } os.close(); InputStream ins = new FileInputStream("test.txt"); int size = ins.available(); for(int i = 0; i < size; i++) { System.out.print((char)ins.read() + " "); } ins.close(); }catch(IOException e) { System.out.print("Exception"); } Example: CopyFile public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close();} } } } Character Streams
  • 5. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ۵ Java Character streams are used to perform input and output for 16-bit unicode. A character stream will read a file character by character. Character streams are appropriate for text files. A character stream needs to be given the file's encoding in order to work properly. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time. Example: import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } BufferedOutputStream
  • 6. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ۶ Java BufferedOutputStream class is used for 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 fast. Example: FileOutputStream fileOut=new FileOutputStream("D:testout.txt"); BufferedOutputStream bufferOut=new BufferedOutputStream(fileOut); String s="Welcome to javaTpoint."; byte b[]=s.getBytes(); bufferOut.write(b); bufferOut.flush(); bufferOut.close(); fileOut.close(); System.out.println("success"); BufferedInputStream BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast. Example: try{ FileInputStream fileIn=new FileInputStream("D:testout.txt"); BufferedInputStream bufferIn=new BufferedInputStream(fileIn); int i; while((i= bufferIn.read())!=-1){ System.out.print((char)i); } String str; while ((str= bufferIn.readLine())!=null) { // for reading a line System.out.println(str); } bufferIn.close(); fileIn.close(); }catch(Exception e){System.out.println(e);} Properties Class
  • 7. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ٧ Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. Normally, Java properties file is used to store project configuration data or settings. Method Description public void load(Reader r) loads data from the Reader object. public void load(InputStream is) loads data from the InputStream object public String getProperty(String key) returns value based on the key. public void setProperty(String key,String value) sets the property in the properties object. public void store(Writer w, String comment) writers the properties in the writer object. public void store(OutputStream os, String comment) writes the properties in the OutputStream object. storeToXML(OutputStream os, String comment) writers the properties in the writer object for generating xml document. public void storeToXML(Writer w, String comment, String encoding) writers the properties in the writer object for generating xml document with specified encoding. Example String filePath = "E: databaseProperties.properties"; Properties properties = new Properties(); FileInputStream fileIn = new FileInputStream(filePath); properties.load(fileIn); fileIn.close(); String mysqlDriver = properties.getProperty("mysql.jdbc.driverClassName"); PrintStream:
  • 8. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ٨ The PrintStream class provides methods to write formatted data to another output stream. It can format primitive types like int, long etc. formatted as text, rather than as their byte values. That is why it is called a PrintStream, because it formats the primitive values as text - like they would look when printed to the screen (or printed to paper). The PrintStream class automatically flushes the data so there is no need to call flush() method. Moreover, its methods don't throw IOException. ‫مثل‬ ‫هايی‬ ‫متغيره‬ ‫مثﻼ‬ .‫نويسد‬ ‫می‬ ‫ديگر‬ ‫خروجی‬ ‫استريم‬ ‫يک‬ ‫به‬ ‫را‬ ‫است‬ ‫خاصی‬ ‫فرمت‬ ‫دارای‬ ‫که‬ ‫را‬ ‫اطﻼعاتی‬ ‫متد‬ ‫اين‬Int‫يا‬Long .‫کرد‬ ‫کپی‬ ‫ديگر‬ ‫استريم‬ ‫يک‬ ‫در‬ ،‫بکنيم‬ ‫بايت‬ ‫به‬ ‫تبديل‬ ‫را‬ ‫آنها‬ ‫ابتدا‬ ‫باشيم‬ ‫مجبور‬ ‫اينکه‬ ‫بدون‬ ‫توان‬ ‫می‬ ‫را‬ Example: import java.io.FileOutputStream; import java.io.PrintStream; public class PrintStreamTest{ public static void main(String args[])throws Exception{ FileOutputStream fout=new FileOutputStream("D:testout.txt "); PrintStream pout=new PrintStream(fout); pout.println(true); pout.println(2016); pout.println((float) 123.456); pout.println("Hello Java"); pout.println("Welcome to Java"); pout.close(); fout.close(); System.out.println("Success?"); } } File Lock:
  • 9. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ٩ In java we have the ability to lock a region of a file or the entire file.The file locking mechanism is handled by the operating system.There are two kinds of file locking: Exclusive: Only one program can hold an exclusive lock on a region of a file. shared: Multiple programs can hold shared locks on the same region of a file. We acquire a lock on a file by using the lock() or tryLock() method of the FileChannel object. If you use these methods without an argument, they lock the entire file. isShared(): The isShared() method of the FileLock object returns true if the lock is shared; otherwise, it returns false. Example: public class Main { public static void main(String[] args) throws Exception { RandomAccessFile raf = new RandomAccessFile("test.txt", "rw"); FileChannel fileChannel = raf.getChannel(); FileLock lock = null; try { lock = fileChannel.lock(); // Lock all file lock = fileChannel.lock(0, 10, false); // Get an exclusive lock first 10 byte lock = fileChannel.tryLock(11, 100, true); // tries to lock first 10 byte on first 10 byte if (lock == null) { // Could not get the lock } else { // Got the lock } } catch (IOException e) { // Handle the exception } finally { if (lock != null) { try { lock.release(); } catch (IOException e) { // Handle the exception } } } } } Serializable:
  • 10. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ١ Serialization in java is a mechanism of writing an object as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies. The reverse operation of serialization is called deserialization. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory. Notice: that for a class to be serialized successfully, two conditions must be met:  The class must implement the java.io.Serializable interface.  All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient. Example: public class Employee implements java.io.Serializable { public String name; public String address; public transient int SSN; public int number; public void mailCheck() { System.out.println("Mailing a check to " + name + " " + address); } } Read and Write Java Objects:
  • 11. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ١ In order to write objects into a file, objects must be converted into byte-stream using ObjectOutputStream. It is mandatory that the concerned class implements Serializable interface. ObjectInputStream can be used to de-serialize and read java objects that have been serialized and written using ObjectOutputStream. Example: public static void main(String[] args) { Person p1 = new Person("John", 30, "Male"); Person p2 = new Person("Rachel", 25, "Female"); try { FileOutputStream f = new FileOutputStream(new File("myObjects.txt")); ObjectOutputStream o = new ObjectOutputStream(f); // Write objects to file o.writeObject(p1); o.writeObject(p2); o.close(); f.close(); FileInputStream fi = new FileInputStream(new File("myObjects.txt")); ObjectInputStream oi = new ObjectInputStream(fi); // Read objects Person pr1 = (Person) oi.readObject(); Person pr2 = (Person) oi.readObject(); System.out.println(pr1.toString()); System.out.println(pr2.toString()); oi.close(); fi.close(); } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Error initializing stream"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintWriter class: PrintWriter class is the implementation of Writer class. It is used to print the formatted representation of objects to the text-output stream.
  • 12. Hamid Ghorbani Java Advanced Tutorial(I/O Streams) https://ir.linkedin.com/in/ghorbanihamid ١ public class PrintWriterExample { public static void main(String[] args) throws Exception { //Data to write on Console using PrintWriter PrintWriter writer = new PrintWriter(System.out); writer.write("Javatpoint provides tutorials of all technology."); writer.flush(); writer.close(); //Data to write in File using PrintWriter PrintWriter writer1 =null; writer1 = new PrintWriter(new File("D:testout.txt")); writer1.write("Like Java, Spring, Hibernate, Android, PHP etc."); writer1.flush(); writer1.close(); } }