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

Unitucerjava

Uploaded by

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

Unitucerjava

Uploaded by

Mohammad kaif
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

I/O Programming

Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required
for input and output operations.
We can perform file handling in Java by Java I/O API.
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations.
These streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations.

Stream
A stream can be defined as a sequence of data. In Java, a stream is composed of bytes. It's called a stream because
it is like a stream of water that continues to flow. There are two kinds of Streams −
•InPutStream − The InputStream is used to read data from a source.
•OutPutStream − The OutputStream is used for writing data to a destination.
Types of Streams:
•Depending on the type of operations, streams can be divided into two primary classes:
• Input Stream: These streams are used to read data that must be taken as an input from a source array or file
or any peripheral device. For eg., FileInputStream, BufferedInputStream, ByteArrayInputStream etc.
• Output Stream: These streams are used to write data as outputs into an array or file or monitor or any output
peripheral device. For eg., FileOutputStream, BufferedOutputStream, ByteArrayOutputStream etc.
Depending on the types of file(the data a stream holds), Streams can be divided into two primary classes:
ByteStream,CharacterStream.
ByteStream: This is used to process data byte by byte (8 bits). Though it has many classes, the FileInputStream
and the FileOutputStream are the most popular ones. The FileInputStream is used to read from the source and
FileOutputStream is used to write to the destination.
Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called InputStream and OutputStream.
Here is the list of various ByteStream Classes:
CharacterStream: In Java, characters are stored using Unicode conventions . Character stream automatically allows
us to read/write data character by character. Though it has many classes, the FileReader and the FileWriter are the
most popular ones. FileReader and FileWriter are character streams used to read from the source and write to the
destination respectively.
Character stream is used to read and write a single character of data.
All the character stream classes are derived from base abstract classes Reader and Writer.
Here is the list of various CharacterStream Classes:
FileInputStream

This class reads the data from a specific file (byte by byte). It is usually used to read the contents of a file with raw
bytes, such as images.

To read the contents of a file using this class −


•First of all, you need to instantiate this class by passing a String variable(path of file) or a File object, representing the
path of the file to be read.

•Then read the contents of the specified file using either of the variants of read() method −
• int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in
integer format).
• This method returns -1 if the end of the file is reached.
• int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current
InputStream, to the given array
• This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached.
• int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as
parameters and reads the contents of the current InputStream, to the given array.
• This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached.
read() Method:
•read() - reads a single byte from the file
•read(byte[] array) - reads the bytes from the file and stores in the specified array
•read(byte[] array, int start, int length) - reads the number of bytes equal to length from the file and stores in the
specified array starting from the position start.

close() Method
To close the file input stream, we can use the close() method.
Once the close() method is called, we cannot use the input stream
to read data.
available() Method
To get the number of available bytes, we can use the available() method.

skip() Method
To discard and skip the specified number of bytes, we can use the skip() method.
FileOutputStream class
FileReader
FileReader is useful to read data in the form of characters from a ‘text’ file.
•This class inherit from the Reader Class.
•FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a
FileInputStream.
Constructors:
•FileReader(File file) – Creates a FileReader , given the File to read from
•FileReader(String fileName) – Creates a new FileReader , given the name of the file to read from
Methods:
•public int read () throws IOException – Reads a single character. This method will block until a character is
available, an I/O error occurs, or the end of the stream is reached.
•public int read(char[] cbuff) throws IOException – Reads characters into an array. This method will block until
some input is available, an I/O error occurs, or the end of the stream is reached.
•public abstract int read(char[] buff, int off, int len) throws IOException –Reads characters into a portion of an
array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
Parameters:
cbuf – Destination buffer
off – Offset at which to start storing characters
len – Maximum number of characters to read
•public void close() throws IOException closes the reader.
•public long skip(long n) throws IOException –Skips characters. This method will block until some characters are
available, an I/O error occurs, or the end of the stream is reached.
Parameters:
n – The number of characters to skip
FileWriter
FileWriter is useful to create a file writing characters into it.
•This class inherits from the Writer class.
•FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a
FileOutputStream.
•FileWriter creates the output file, if it is not present already.
Java DataInputStream Class
Java DataInputStream class allows an application to read primitive data from the input stream in a machine-
independent way.
class DataOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
//writing the data using DataOutputStream
try ( DataOutputStream dout =
new DataOutputStream(new FileOutputStream("file.dat")) )
{
dout.writeDouble(1.1);
dout.writeInt(55);
dout.writeBoolean(true);
dout.writeChar('4');
}
catch(FileNotFoundException ex)
{
System.out.println("Cannot Open the Output File");
return;
}

// reading the data back using DataInputStream


try ( DataInputStream din =
new DataInputStream(new FileInputStream("file.dat")) )
{
double a = din.readDouble();
int b = din.readInt();
boolean c = din.readBoolean();
char d=din.readChar();
System.out.println("Values: " + a + " " + b + " " + c+" " + d);
}
catch(FileNotFoundException e)
{
System.out.println("Cannot Open the Input File");
return;
}
}
}
Output:1.1 55 true 4
Java DataOutputStream Class
Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a
machine-independent way.
Java BufferedInputStream Class
Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make
the performance fast.
The important points about BufferedInputStream are:
•When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained
input stream, many bytes at a time.
•When a BufferedInputStream is created, an internal buffer array is created.
Java BufferedOutputStream Class
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. The flush() flushes
the data of one stream and send it into another. It is required if you have connected the one stream with another.
Java SequenceInputStream Class
Java SequenceInputStream class is used to read data from multiple streams. It reads data sequentially (one by
one).
Java SequenceInputStream Class declaration
File class:
File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting files.

The File class from the java.io package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory name

import java.io.File; // Import the File class


File myObj = new File("filename.txt"); // Specify the filename
Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the
file was successfully created, and false if the file already exists. Note that the method is enclosed in
a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be
created for some reason):
To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes
to escape the "\" character (for Windows). On Mac and Linux you can just write the path, like:
/Users/name/filename.txt
File myObj = new File("C:\\Users\\MyName\\filename.txt");
There are many available classes in the Java API that can be used to read and write files in Java:
FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter,
FileOutputStream, etc.
Which one to use depends on the Java version you're working with and whether you need to read bytes or
characters, and the size of the file/lines etc.
Following is the example for reading data from the file using Scanner class:
Java - RandomAccessFile
This class is used for reading and writing to random access file. In java, the java.io package has a built-in
class RandomAccessFile that enables a file to be accessed randomly. The RandomAccessFile class has several
methods used to move the cursor position in a file.If end-of-file is reached before the desired number of byte has been
read than EOFException is thrown. It is a type of IOException.
RandomAccessFile methods
import java.io.RandomAccessFile;
import java.io.IOException;

public class RandomAccessFileExample {


static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();

You might also like