Iostreams 171014073212
Iostreams 171014073212
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, It is used to write len bytes from the byte array starting at offset off to
int len) 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.
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.
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.
۴
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
FileInputStream in = null;
try {
in = new FileInputStream("input.txt");
int c;
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 {
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(InputStream is) loads data from the InputStream object
public void setProperty(String key,String sets the property in the properties object.
value)
public void store(Writer w, String comment) writers the properties in the writer object.
public void store(OutputStream os, String writes the properties in the OutputStream object.
comment)
storeToXML(OutputStream os, String writers the properties in the writer object for
comment) generating xml document.
public void storeToXML(Writer w, String writers the properties in the writer object for
comment, String encoding) 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.
Long ياInt مثﻼ متغيره هايی مثل.اين متد اطﻼعاتی را که دارای فرمت خاصی است را به يک استريم خروجی ديگر می نويسد
. در يک استريم ديگر کپی کرد،را می توان بدون اينکه مجبور باشيم ابتدا آنها را تبديل به بايت بکنيم
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:
Example:
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
١
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:
// 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