ognio
ognio
• 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.
• A stream is 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.
• System.out.println("simple message");
• System.err.println("error message");
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.
Working of Java OutputStream and InputStream
OutputStream class:
OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes. An output stream accepts output
bytes and sends them to some sink.
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
Method Description
1) public abstract int read()throws reads the next byte of data from the input
IOException stream. It returns -1 at the end of the file.
3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy
Java FileOutputStream Class
If you have to write primitive values into a file, use FileOutputStream class. You can write
byte-oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutputStream.
Method Description
protected void finalize() It is used to clean up the connection with
the file output stream.
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.
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.
import java.io.FileOutputStream;
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public class FileOutputStreamExample {
public static void main(String args[]){
public static void main(String args[]){
try{
try{
FileOutputStream fout=new
FileOutputStream fout=new
FileOutputStream("D:\\ab.txt");
FileOutputStream("D:\\abc.txt");
String s=“World";
fout.write(65);
byte b[]=s.getBytes();//converting string into byte array
fout.close();
fout.write(b);
System.out.println("success...");
fout.close();
}catch(Exception e){System.out.println(e);}
System.out.println("success...");
}
}catch(Exception e){System.out.println(e);}
}
}
}
Output:
Output:
Success...
Success... The content of a text file ab.txt is set with the data
The content of a text file abc.txt is set with the data A. World
ab.txt ab.txt
A World
Java FileInputStream Class
Java 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.
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Before running the code, a text file named as “ab.txt" is required to be created. In this file,
we are having following content:
World
After executing the above program, you will get a single character from the file which is 87
(in byte form). To see the text, you need to convert it into character.
Output:
W
Read all characters
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\ab.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
World
import java.io.*;
public class CopyFile {
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) { Let's have a file input.txt with the following content −
out.write(c);
} This is test for copy file.
}finally {
if (in != null) { As a next step, compile the above program and execute it,
in.close(); which will result in creating output.txt file with the same
} content as we have in input.txt. So let's put the above code in
if (out != null) { CopyFile.java file and do the following −
out.close();
} $javac CopyFile.java
} $java CopyFile
}
}
Java BufferedOutputStream class
• It 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.
Constructor Description
testout.txt 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.
Welcome
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.
Constructor Description
Method Description
int available() It returns an estimate number of bytes that can be read from the
input stream without blocking by the next invocation method for the
input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream into a
specified byte array, starting with the given offset.
void close() It closes the input stream and releases any of the system resources
associated with the stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\test.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
HelloWorld
Output:
HelloWorld
Java DataOutputStream class allows an application to write primitive Java data types to
the output stream in a machine-independent way.
Java DataInputStream class allows an application to read primitive data from the input
stream in a machine-independent way.
void write(int b) It is used to write the specified byte to the underlying output stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeChars(String s) It is used to write string to the output stream as a sequence of characters.
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.
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 char value.
double readDouble() It is used to read eight input bytes and returns a double value.
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, It is used to read len bytes from the input stream.
import java.io.*; import java.io.*;
public class OutputExample { public class DataStreamExample {
public static void main(String[] args) throws IOException public static void main(String[] args) throws IOException {
{ InputStream input = new FileInputStream("D:\\testout.txt");
FileOutputStream file = new DataInputStream inst = new DataInputStream(input);
FileOutputStream(D:\\testout.txt); int count = input.available();
DataOutputStream data = new DataOutputStream(file); byte[] ary = new byte[count];
data.writeInt(65); inst.read(ary);
data.flush(); for (byte bt : ary) {
data.close(); char k = (char) bt;
System.out.println("Succcess..."); System.out.print(k+"-");
} }
} }
}
Output:
Here, we are assuming that you have following data in
Succcess... "testout.txt" file:
testout.txt:
JAVA
A Output:
J-A-V-A
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
for (byte b : u) {
dos.writeChar(b);
//write data in file char format.
System.out.println("Successfully Write");
}
dos.flush();
} Output:
catch(Exception r) {
System.out.println(r); Successfully Write
} Successfully Write
}}
import java.io.DataInputStream; // force bytes to the underlying stream
import java.io.DataOutputStream; dos.flush();
import java.io.FileInputStream; // create file input stream
import java.io.FileOutputStream; is = new FileInputStream("c:\\test.txt");
import java.io.IOException; // create new data input stream
import java.io.InputStream; dis = new DataInputStream(is);
// read till end of the stream
public class DataInputStreamDemo { while(dis.available()>0) {
public static void main(String[] args) throws IOException { // read character
InputStream is = null; char c = dis.readChar();
DataInputStream dis = null; // print
FileOutputStream fos = null; System.out.print(c);
DataOutputStream dos = null; }
byte[] buf = {65,66,67,68,69,70}; } catch(Exception e) {e.printStackTrace();
try { } finally {
// create file output stream // releases all system resources from the streams
fos = new FileOutputStream("c:\\test.txt"); if(is!=null)
// create data output stream is.close();
dos = new DataOutputStream(fos); if(dos!=null)
// for each byte in the buffer is.close();
for (byte b:buf) { if(dis!=null)
// write character to the dos dis.close();
dos.writeChar(b); if(fos!=null)
} fos.close(); } } }
Java FileWriter Class
Java FileWriter class is used to write character-oriented data to a file. It is character-oriented
class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array
because it provides method to write string directly.
Constructor Description
import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[])
{
try{
FileWriter fw=new FileWriter("D:\\abc.txt"); Output:
fw.write("Welcome");
fw.close(); Success...
}catch(Exception e){System.out.println(e);}
System.out.println("Success..."); testout.txt:
} Welcome
}
Java FileReader Class
Java FileReader class is used to read data from the file. It is character-oriented class which
is used for file handling in java.
Constructor Description
FileReader(String file) It gets filename in string. It opens the given file in read
mode. If file doesn't exist, it throws FileNotFoundException.
FileReader(File file) It gets filename in file instance. It opens the given file in read
mode. If file doesn't exist, it throws FileNotFoundException.
Method Description
int read() It is used to return a character in ASCII form. It returns -1 at the end of file.
void close() It is used to close the FileReader class.
import java.io.FileReader;
public class FileReaderExample
{
public static void main(String args[])throws Exception
{
FileReader fr=new FileReader("D:\\abc.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Output:
Welcome
import java.io.*;
public class CopyFile {
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();
}
}
}
}
import java.io.*;
public class ReadConsole {
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c; Let's keep the above code in ReadConsole.java file and try to
do { compile and execute it as shown in the following program. This
c = (char) cin.read(); program continues to read and output the same character until
System.out.print(c); we press 'q' −
} while(c != 'q');
}finally { $javac ReadConsole.java
if (cin != null) { $java ReadConsole
cin.close(); Enter characters, 'q' to quit.
} 1
} 1
} e
} e
q
q
Java File Class
The File class is an abstract representation of file and directory pathname. A pathname can
be either absolute or relative.
The File class have several methods for working with directories and files such as creating
new directories or files, deleting and renaming directories or files, listing the contents of a
directory etc.
String getName() It returns the name of the file or directory denoted
by this abstract pathname.
String getParent() It returns the pathname string of this abstract
pathname's parent, or null if this pathname does not
name a parent directory.
boolean isAbsolute() It tests whether this abstract pathname is absolute.
boolean mkdir() It creates the directory named by this abstract
pathname.
boolean createNewFile() It atomically creates a new, empty file named by this
abstract pathname if and only if a file with this name
does not yet exist.
import java.io.*;
public class FileDemo {
public static void main(String[] args) {
try {
File file = new File("abc.txt");
if (file.createNewFile()) {
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
boolean canWrite() It tests whether the application can modify the file denoted by this
abstract pathname.String[]
boolean canExecute() It tests whether the application can execute the file denoted by this
abstract pathname.
boolean canRead() It tests whether the application can read the file denoted by this abstract
pathname.
boolean isAbsolute() It tests whether this abstract pathname is absolute.
boolean isDirectory() It tests whether the file denoted by this abstract pathname is a directory.
boolean isFile() It tests whether the file denoted by this abstract pathname is a normal file.