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

ognio

Java I/O (Input and Output) utilizes streams for efficient data processing, with the java.io package providing necessary classes for file handling. The document details various classes such as OutputStream, InputStream, FileOutputStream, and FileInputStream, along with their methods for reading and writing data. Additionally, it covers BufferedOutputStream and BufferedInputStream for enhanced performance, as well as DataOutputStream and DataInputStream for handling primitive data types.

Uploaded by

aditi21paul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

ognio

Java I/O (Input and Output) utilizes streams for efficient data processing, with the java.io package providing necessary classes for file handling. The document details various classes such as OutputStream, InputStream, FileOutputStream, and FileInputStream, along with their methods for reading and writing data. Additionally, it covers BufferedOutputStream and BufferedInputStream for enhanced performance, as well as DataOutputStream and DataInputStream for handling primitive data types.

Uploaded by

aditi21paul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Java I/O

• 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.

• 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.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream


Java I/O
Let's see the code to print output and an error message to the console.

• System.out.println("simple message");
• System.err.println("error message");

Code to get input from console.


int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character

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.

Useful methods of OutputStream:


Method Description

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


IOException current output stream.
2) public void write(byte[])throws is used to write an array of byte to
IOException the current output stream.
3) public void flush()throws flushes the current output stream.
IOException
4) public void close()throws is used to close the current output
IOException stream.
OutputStream Hierarchy
InputStream class

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.

2) public int available()throws IOException returns an estimate of the number of bytes


that can be read from the current input
stream.

3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy
Java FileOutputStream Class

Java FileOutputStream is an output stream used for writing data to a file.

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.

FileOutputStream class declaration

public class FileOutputStream extends OutputStream


FileOutputStream class methods

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.

Declaration for java.io.FileInputStream class:


public class FileInputStream extends InputStream
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 It is used to read up to len bytes of data from the input
len) 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.
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.
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new
FileInputStream("D:\\ab.txt");
int i=fin.read();
System.out.print((char)i);

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 {

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) { 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.

For adding the buffer in an OutputStream, use the BufferedOutputStream class.

Syntax for adding the buffer in an OutputStream:


OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));

Constructor Description

BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is


used for writing the data to the specified output
stream.
BufferedOutputStream(OutputStream os, int size) It creates the new buffered output stream which is
used for writing the data to the specified output stream
with a specified buffer size.
Java BufferedOutputStream class
Method Description

void write(int b) It writes the specified byte to the buffered output


stream.
void write(byte[] b, int off, int len) It write the bytes from the specified byte-input
stream into a specified byte array
, starting with the given offset
void flush() It flushes the buffered output stream.
Java BufferedOutputStream class
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Output:
We are writing the textual information in the BufferedOutputStream object
Success which is connected to the FileOutputStream object.

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

BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it


argument, the input stream IS, for later use.
BufferedInputStream(InputStream IS, int size) It creates the BufferedInputStream with a specified
buffer size and saves it argument, the input stream
IS, for later use.
BufferedInputStream class methods

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);}
}
}

we are assuming that you have following data in "test.txt" file:

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 DataOutputStream class declaration:

public class DataOutputStream extends FilterOutputStream implements DataOutput

Java DataInputStream class allows an application to read primitive data from the input
stream in a machine-independent way.

Declaration for java.io.DataInputStream class:


public class DataInputStream extends FilterInputStream implements DataInput
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, 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.

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.
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 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;

public class TestExp {


public static void main(String[] args) throws IOException {
try {
FileOutputStream f = new
FileOutputStream("E:\\users\\file.txt");
DataOutputStream dos = new DataOutputStream(f);
byte[] u = { 67, 78, };

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.

Declaration for Java.io.FileWriter class:


public class FileWriter extends OutputStreamWriter

Constructor Description

FileWriter(String file) Creates a new file. It gets file name in string


.
FileWriter(File file) Creates a new file. It gets file name in File object
Method Description

void write(String text) It is used to write the string into FileWriter.


void write(char c) It is used to write the char into FileWriter.
void write(char[] c) It is used to write char array into FileWriter.
void flush() It is used to flushes the data of FileWriter.
void close() It is used to close the FileWriter.

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.

Declaration for Java.io.FileReader class:


public class FileReader extends InputStreamReader

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 {

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();
}
}
}
}
import java.io.*;
public class ReadConsole {

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


InputStreamReader cin = null;

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy