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

CSE307_Unit3_Java Input and Output

The document provides an overview of Java I/O, explaining the use of streams for input and output operations. It details the classes and methods associated with OutputStream and InputStream, including FileOutputStream and FileInputStream, for file handling. Additionally, it introduces the File class for managing files and directories, and the RandomAccessFile class for random access file operations.
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

CSE307_Unit3_Java Input and Output

The document provides an overview of Java I/O, explaining the use of streams for input and output operations. It details the classes and methods associated with OutputStream and InputStream, including FileOutputStream and FileInputStream, for file handling. Additionally, it introduces the File class for managing files and directories, and the RandomAccessFile class for random access file operations.
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/ 10

Java Programming

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.

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

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

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

Let's see the 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 vs InputStream
The explanation of OutputStream and InputStream classes are given below:

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.

Let's understand the working of Java OutputStream and InputStream by the figure given below.
Java Programming

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 current output


IOException stream.

2) public void write(byte[])throws is used to write an array of byte to the current


IOException 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 stream.


IOException
Java Programming
OutputStream Hierarchy

InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input stream
of bytes.

Useful methods of InputStream

Method Description

1) public abstract int reads the next byte of data from the input stream. It
read()throws IOException returns -1 at the end of the file.

2) public int available()throws returns an estimate of the number of bytes that can
IOException be read from the current input stream.

3) public void close()throws is used to close the current input stream.


IOException

InputStream Hierarchy
Java Programming

FileOutputStream Class
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.

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 It is used to write len bytes from the byte array starting at
off, int len) 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

import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s = "Welcome to java files.";
byte b[] = s.getBytes();//converting string into byte array
fout.write(b);
Java Programming
fout.close();
System.out.println("success...");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:
Success...
The content of a text file testout.txt is set with the data Welcome to javaTpoint.

testout.txt
Welcome to java files.

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.
public class FileInputStream extends InputStream

FileInputStream class methods

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 It is used to read up to len bytes of data from the input stream.
off, int len)

long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.

FileChannel It is used to return the unique FileChannel object associated


getChannel() with the file input stream.

FileDescriptor getFD() It is used to return the FileDescriptor object.

protected void It is used to ensure that the close method is call when there is
finalize() no more reference to the file input stream.

void close() It is used to closes the stream.

Example
import java.io.FileInputStream;
Java Programming
public class DataStreamExample
{
public static void main(String args[])
{
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);
}
}
}

Output:

Welcome to java files.

Byte Streams

Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of these
two classes to copy an input file into an output file −

Example
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)
{
out.write(c);
}
}
finally
{
if (in != null)
{
in.close();
Java Programming
}
if (out != null)
{
out.close();
}
}
}
}

Now let's have a file input.txt with the following content −

This is a test for copy file.

As a next step, compile the above program and execute it, which will result in creating an output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file
and do the following −

$javac CopyFile.java

$java CopyFile

Character Streams

Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit Unicode. 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.

We can re-write the above example, which makes the use of these two classes to copy an input
file (having Unicode characters) into an output file −

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);
}
}
Java Programming
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}

Now let's have a file input.txt with the following content −

This is test for copy file.

As a next step, compile the above program and execute it, which will result in creating an output.txt
file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file
and do the following −

$javac CopyFile.java

$java CopyFile

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.

Constructor Description

File(File parent, String It creates a new File instance from a parent abstract pathname
child) and a child pathname string.

File(String pathname) It creates a new File instance by converting the given pathname
string into an abstract pathname.

File(String parent, It creates a new File instance from a parent pathname string
String child) and a child pathname string.

File(URI uri) It creates a new File instance by converting the given file: URI
into an abstract pathname.
Java Programming

Methods
Modifier Method Description
and Type

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.

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

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.

File[] listFiles() It returns an array of abstract pathnames denoting


the files in the directory denoted by this abstract
pathname

String[] list(FilenameFilter It returns an array of strings naming the files and


filter) directories in the directory denoted by this abstract
pathname that satisfy the specified filter.

boolean mkdir() It creates the directory named by this abstract


pathname.

Example

import java.io.*;
public class FileDemo
{
public static void main(String[] args)
{
try
{
File file = new File("javaFile123.txt");
if (file.createNewFile())
{
System.out.println("New File is created!");
}
Java Programming
else
{
System.out.println("File already exists.");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Output:

New File is created!

RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves like
a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor
we do the read write operations. 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.

Constructor Description

RandomAccessFile(File Creates a random access file stream to read from,


file, Stringmode) and optionally to write to, the file specified by the File
argument.

RandomAccessFile(String name, Creates a random access file stream to read from,


String mode) and optionally to write to, a file with the specified
name.

Methods

Modifier Method Method


and Type

void close() It closes this random access file stream and


releases any system resources associated with
the stream.

int readInt() It reads a signed 32-bit integer from this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or
write occurs.

void writeDouble(double It converts the double argument to a long using


v) the doubleToLongBits method in class Double,
and then writes that long value to the file as an
eight-byte quantity, high byte first.

You might also like