0% found this document useful (0 votes)
5 views37 pages

FILES

The document provides an overview of Java I/O, explaining the concept of streams for input and output operations, including the standard input (System.in), output (System.out), and error (System.err) streams. It details the types of streams, specifically byte and character streams, and describes various classes such as FileInputStream and FileOutputStream for file handling. Additionally, it includes examples of reading from and writing to files, as well as methods associated with different stream classes.
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)
5 views37 pages

FILES

The document provides an overview of Java I/O, explaining the concept of streams for input and output operations, including the standard input (System.in), output (System.out), and error (System.err) streams. It details the types of streams, specifically byte and character streams, and describes various classes such as FileInputStream and FileOutputStream for file handling. Additionally, it includes examples of reading from and writing to files, as well as methods associated with different stream classes.
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/ 37

FILES

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.

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

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character

System.in

System.in is an InputStream which is typically connected to keyboard input of console


programs. In other words, if you start a Java application from the command line, and you
type something on the keyboard while the CLI console (or terminal) has focus, the
keyboard input can typically be read via System.in from inside that Java application.
However, it is only keyboard input directed to that Java application (the console /
terminnal that started the application) which can be read via System.in. Keyboard input for
other applications cannot be read via System.in .

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
System.in is not used as often since data is commonly passed to a command line Java
application via command line arguments, files, or possibly via network connections if the
application is designed for that. In applications with GUI the input to the application is
given via the GUI. This is a separate input mechanism from System.in.

System.out

System.out is a PrintStream to which you can write characters. System.out normally


outputs the data you write to it to the CLI console / terminal. System.out is often used from
console-only programs like command line tools as a way to display the result of their
execution to the user. This is also often used to print debug statements of from a program
(though it may arguably not be the best way to get debug info out of a program).

System.err

System.err is a PrintStream. System.err works like System.out except it is normally only


used to output error texts. Some programs (like Eclipse) will show the output
to System.err in red text, to make it more obvious that it is error text.

Why We Need IO Streams in Java?

In day-to-day work, we do not enter the input into the programs manually. Also, the result
of the program needs to be stored somewhere for further use.

So, IO streams in Java provide us with input and output streams that help us to extract data
from the files and write the data into the files. Normally, we can create, delete, and edit files
using Java.io.

In short, all the file manipulation is done using Java IO streams.

Types of Streams in Java

 Byte stream

 Character Stream.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
ByteStream Classes in Java

ByteStream classes are used to read bytes from the input stream and write bytes to the
output stream. In other words, we can say that ByteStream classes read/write the data of
8-bits. We can store video, audio, characters, etc., by using ByteStream classes. These
classes are part of the java.io package.

The ByteStream classes are divided into two types of classes, i.e., InputStream and
OutputStream. These classes are abstract and the super classes of all the Input/Output
stream classes.

InputStream Class

The InputStream class provides methods to read bytes from a file, console or memory. It is
an abstract class and can't be instantiated; however, various classes inherit the
InputStream class and override its methods. The subclasses of InputStream class are given
in the following table.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
SN Class Description

1 BufferedInputStream This class provides methods to read bytes from the buffer.

2 ByteArrayInputStream This class provides methods to read bytes from the byte array.

3 DataInputStream This class provides methods to read Java primitive data types.

4 FileInputStream This class provides methods to read bytes from a file.

5 FilterInputStream This class contains methods to read bytes from the other input
streams, which are used as the primary source of data.

6 ObjectInputStream This class provides methods to read objects.

7 PipedInputStream This class provides methods to read from a piped output stream to
which the piped input stream must be connected.

8 SequenceInputStream This class provides methods to connect multiple Input Stream and
read data from them.

The InputStream class contains various methods to read the data from an input stream.
These methods are overridden by the classes that inherit the InputStream class. However,
the methods are given in the following table.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
SN Method Description

1 int read() This method returns an integer, an integral representation of the next
available byte of the input. The integer -1 is returned once the end of
the input is encountered.

2 int read (byte This method is used to read the specified buffer length bytes from the
buffer []) input and returns the total number of bytes successfully read. It returns
-1 once the end of the input is encountered.

3 int read (byte This method is used to read the 'nBytes' bytes from the buffer starting
buffer [], int loc, at a specified location, 'loc'. It returns the total number of bytes
int nBytes) successfully read from the input. It returns -1 once the end of the input
is encountered.

4 int available () This method returns the number of bytes that are available to read.

5 Void mark(int This method is used to mark the current position in the input stream
nBytes) until the specified nBytes are read.

6 void reset () This method is used to reset the input pointer to the previously set
mark.

7 long skip (long This method is used to skip the nBytes of the input stream and returns
nBytes) the total number of bytes that are skipped.

8 void close () This method is used to close the input source. If an attempt is made to
read even after the closing, IOException is thrown by the method.

OutputStream Class

The OutputStream is an abstract class that is used to write 8-bit bytes to the stream. It is
the superclass of all the output stream classes. This class can't be instantiated; however, it
is inherited by various subclasses that are given in the following table.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
SN Class Description

1 BufferedOutputStream This class provides methods to write the bytes to the buffer.

2 ByteArrayOutputStream This class provides methods to write bytes to the byte array.

3 DataOutputStream This class provides methods to write the java primitive data types.

4 FileOutputStream This class provides methods to write bytes to a file.

5 FilterOutputStream This class provides methods to write to other output streams.

6 ObjectOutputStream This class provides methods to write objects.

7 PipedOutputStream It provides methods to write bytes to a piped output stream.

8 PrintStream It provides methods to print Java primitive data types.

SN Method Description

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
1 void write (int i) This method is used to write the specified single byte to the output
stream.

2 void write (byte buffer It is used to write a byte array to the output stream.
[] )

3 Void write(bytes It is used to write nByte bytes to the output stream from the buffer
buffer[],int loc, int starting at the specified location.
nBytes)

4 void flush () It is used to flush the output stream and writes the pending buffered
bytes.

5 void close () It is used to close the output stream. However, if we try to close the
already closed output stream, the IOException will be thrown by this
method.

The OutputStream class provides various methods to write bytes to the output streams.
The methods are given in the following table.

Example:

The following example uses the ByteArrayInputStream

to create an input stream from a byte array "content". We use the read() method to read
the content from an input stream. We have also used the write() method on a
FileOutputStream object to write the byte array content in the file.

FileInputStream Class in Java


This stream is used to read the content of the specified file byte by byte. 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. It extends the
InputStream abstract class.
Creating FileInputStream object:
FileInputStream fis = new FileInputStream(“filename”);
Sample Program to understand FileInputStream class
import java.io.FileInputStream;

public class FileInputStreamDemo

{
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
public static void main (String[]args)

try

FileInputStream fis = new FileInputStream ("input.txt");

System.out.println ("Data in the file: ");

// Reads the first byte

int ch = fis.read ();

while (ch != -1)

System.out.print ((char) ch);

// Reads next byte from the file

ch = fis.read ();

fis.close ();

catch (Exception e)

e.getStackTrace ();

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Output: Suppose we have a file named input.txt
Data in the file:
This is a line of text inside the file
Note: While reading the data from a file if the specified file is not available then it will
throw a run time exception called FileNotFoundException. fis.read() method returns -1 if
there are no bytes to read which is nothing but the end position of the file.
Methods of FileInputStream Class
1. int available(): It is used to return the estimated number of bytes that can be read
from the input stream.
2. int read(): It is used to read the byte of data from the input stream.
3. int read(byte[] b): It is used to read up to b.length bytes of data from the input
stream.
4. int read(byte[] b, int off, int len): It is used to read up to len bytes of data from the
input stream.
5. long skip(long x): It is used to skip over and discard x bytes of data from the input
screen.
6. protected void finalize(): It is used to ensure that the close method is called when
there is no more reference to the file input stream.
7. void close(): It is used to closes the stream.

FileOutputStream Class in Java


This byte stream is used to write the content onto a file byte by byte. It extends the
OutputStream abstract class. If you have to write primitive values into a file, use the
FileOutputStream class.
Creating FileOutputStream object:
Syntax1: FileOutputStream fos = new FileOutputStream(“filename”); This syntax will
create the file if the specified file is not available and write the content otherwise if the file
is available then it will overwrite the old content with new content.
Syntax2: FileOutputstream fos = new FileOutputStream(“filename”, true); This syntax
will create the file if the specified file is not available and write the content otherwise if the
file is available then it will append old content with new content.
Example: Program to understand FileOutputStream class
import java.io.*;

public class FileOutputStreamDemo

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

FileOutputStream fos = new FileOutputStream ("output.txt", true);

DataInputStream dis = new DataInputStream (System.in);

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
char ch;

System.out.println ("Enter chars and press # to save");

ch = (char) dis.read ();

while (ch != '#')

fos.write (ch);

ch = (char) dis.read ();

// Releasing the resources

fos.close ();

dis.close ();

Output:

output.txt: HI
Note: While writing data onto a file if the specified file is not available then it won’t throw
any run time exception saying FileNotFoundException instead of this it will create the file
with the specified name. But it will throw FileNotFoundException if the specified location is
not available.
Methods of FileOutputStream Class
1. protected void finalize(): It is used to clean up the connection with the file output
stream.
2. void write(byte[] ary): It is used to write ary.length bytes from the byte array to
the file output stream.
3. 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.
4. void write(int b): It is used to write the specified byte to the file output stream.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
5. void close(): It is used to closes the file output stream.
Example: Program to copy the content of one file into another file in Java
import java.io.*;

public class FileCopyDemo

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

FileInputStream fis = new FileInputStream("input.txt");

FileOutputStream fos = new FileOutputStream("output.txt");

int ch;

ch = fis.read();

while(ch!= -1) {

fos.write(ch);

ch = fis.read();

fis.close();

fos.close();

System.out.println("\nFile Copied Successfully");

Output: File Copied Successfully

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
ByteArrayInputStream Class in Java
ByteArrayInputStream is a byte stream class that is used to read the bytes of byte array
byte by byte. It extends the InputStream abstract class. In ByteArrayInputStream, the input
stream is created using the array of bytes. It includes an internal array to store data of that
particular byte array.
Creating ByteArrayInputStream Object:
ByteArrayInputStream bais = new ByteArrayInputStream(byte[]);
Example: Program to understand ByteArrayInputStream class in Java
import java.io.*;

public class ByteArrayInputStreamDemo

public static void main(String[] args) {

String str = "Hello World";

byte arrb[] = str.getBytes();

ByteArrayInputStream bais = new ByteArrayInputStream(arrb);

int ch;

ch = bais.read();

while (ch != -1) {

System.out.print((char) ch);

ch = bais.read();
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
}

Output: Hello World


Note: Here read() method returns -1 if there are no bytes to read which means it reaches to
end position.
Methods of ByteArrayInputStream Class
1. int read(): Reads the single byte from the array present in the input stream.
2. int read (byte[] array): Reads bytes from the input stream and stores them in the
specified array.
3. int read(byte[] array, int start, int length): Reads the number of bytes equal to
length from the stream and stores in the specified array starting from the position
start.
4. int available(): To get the number of available bytes in the input stream.
5. long skip(long x): It is used to skip the x bytes of input from the input stream.
6. void close() : It is used for closing a ByteArrayInputStream.
7. void mark(): It is used to set the currently marked position in the stream.

ByteArrayOutputStream Class in Java


The ByteArrayOutputStream class of the java.io package can be used to write an array of
output data (in bytes). It extends the OutputStream abstract class. ByteArrayOutputStream
maintains an internal array of bytes to store the data.
Creating ByteArrayOutputStream Object:
ByteArrayOutputStream out = new ByteArrayOutputStream();

Example: Program to understand ByteArrayOutputStream Class in Java


import java.io.*;

public class ByteArrayOutputStreamDemo

public static void main(String[] args) {

String data = "Hello World";

try {

// Creates an output stream

ByteArrayOutputStream out = new ByteArrayOutputStream();


Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
byte[] array = data.getBytes();

// Writes data to the output stream

out.write(array);

// Retrieves data from the output stream in string format

String streamData = out.toString();

System.out.println("Output stream: " + streamData);

out.close();

catch(Exception e) {

e.getStackTrace();

Output: Output stream: Hello World


Methods of ByteArrayOutputStream Class in Java
1. void write(int b): Writes the specified byte to the output stream.
2. void write(byte[] array): Writes the bytes from the specified array to the output
stream.
3. void write(byte[] arr, int start, int length): Writes the number of bytes equal to
length to the output stream from an array starting from the position start.
4. void writeTo(OutputStream out): It is used for writing the complete content of a
byte array output stream to the specified output stream.
5. String toString(): It is used for converting the content into string decoding bytes
using a platform default character set.
6. byte toByteArray(): returns the array present inside the output stream.
7. void close(): It is used to close the ByteArrayOutputStream.
8. int size(): It is used to returns the current size of a buffer.

DataInputStream Class in Java


DataInputStream is a byte stream class which is used to perform reading operation from
any input device like keyboard, file, etc. Java DataInputStream class allows an application to
read primitive data from the input stream in a machine-independent way.
Creating DataInputStream Object:
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
DataInputStream dis = new DataInputStream(resource);
Example: Program to understand DataInputStream class in Java
import java.io.*;

public class DataInputStreamDemo

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

DataInputStream dis = new DataInputStream(System.in);

System.out.println("Enter any string");

String str = dis.readLine(); //parsing

System.out.println("str="+str);

System.out.println("Enter any Integer");

int i= Integer.parseInt(dis.readLine()); //parsing

System.out.println("i="+i);

System.out.println("Enter any Double");

double d = Double.parseDouble(dis.readLine());

System.out.println("d="+d);

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Output

DataOutputStream Class in Java

Java DataOutputStream class allows an application to write primitive Java data types to the
output stream in a machine-independent way. Java application generally uses the data
output stream to write data that can later be read by a data input stream.
Creating DataOutputStream
Object: DataOutputStream data = new DataOutputStream(resource);
Example: Program to understand DataOutputStream class in Java
import java.io.*;

public class DataOutputStreamDemo

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

FileOutputStream file = new FileOutputStream("input.txt");

DataOutputStream data = new DataOutputStream(file);

data.writeInt(65);

data.flush();

data.close();

System.out.println("Succcess...");

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
}

Output: Succcess…
input.txt
A

BufferedInputStream Class in Java

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:

o 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.
o When a BufferedInputStream is created, an internal buffer array is created.

Java BufferedInputStream class declaration

Let's see the declaration for Java.io.BufferedInputStream class:

1. public class BufferedInputStream extends FilterInputStream

Java BufferedInputStream class constructors

Constructor Description

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


argument, the input stream IS, for later use.

BufferedInputStream(InputStream IS, It creates the BufferedInputStream with a specified


int size) buffer size and saves it argument, the input stream IS,
for later use.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Java 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 It read the bytes from the specified byte-input stream into a specified
off, int ln) 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.

void reset() It repositions the stream at a position the mark method was last called
on this input stream.

void mark(int It sees the general contract of the mark method for the input stream.
readlimit)

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

boolean It tests for the input stream to support the mark and reset methods.
markSupported()

Example of Java BufferedInputStream

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
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.

For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see
the syntax for adding the buffer in an OutputStream:

1. OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\t


estout.txt"));
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
Java BufferedOutputStream class declaration

Let's see the declaration for Java.io.BufferedOutputStream class:

1. public class BufferedOutputStream extends FilterOutputStream

Java BufferedOutputStream class constructors

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, It creates the new buffered output stream which is


int size) used for writing the data to the specified output
stream with a specified buffer size.

Java BufferedOutputStream class methods

Method Description

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

void write(byte[] b, int off, It write the bytes from the specified byte-input stream into a specified
int len) byte array, starting with the given offset

void flush() It flushes the buffered output stream.

Example of BufferedOutputStream class:

In this example, we are writing the textual information in the BufferedOutputStream object
which is connected to the FileOutputStream object. The flush() flushes the data of one

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
stream and send it into another. It is required if you have connected the one stream with
another.

1. package com.javatpoint;
2. import java.io.*;
3. public class BufferedOutputStreamExample{
4. public static void main(String args[])throws Exception{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. BufferedOutputStream bout=new BufferedOutputStream(fout);
7. String s="Welcome to javaTpoint.";
8. byte b[]=s.getBytes();
9. bout.write(b);
10. bout.flush();
11. bout.close();
12. fout.close();
13. System.out.println("success");
14. }
15. }

Output:

Success

testout.txt

Welcome to javaTpoint.

CharacterStream Classes in Java

The java.io package provides CharacterStream classes to overcome the limitations of


ByteStream classes, which can only handle the 8-bit bytes and is not compatible to work
directly with the Unicode characters. CharacterStream classes are used to work with 16-bit
Unicode characters. They can perform operations on characters, char arrays and Strings.

However, the CharacterStream classes are mainly used to read characters from the source
and write them to the destination. For this purpose, the CharacterStream classes are
divided into two types of classes, I.e., Reader class and Writer class.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Reader Class

Reader class is used to read the 16-bit characters from the input stream. However, it is an
abstract class and can't be instantiated, but there are various subclasses that inherit the
Reader class and override the methods of the Reader class. All methods of the Reader class
throw an IOException. The subclasses of the Reader class are given in the following table.

SN Class Description

1. BufferedReader This class provides methods to read characters from the buffer.

2. CharArrayReader This class provides methods to read characters from the char array.

3. FileReader This class provides methods to read characters from the file.

4. FilterReader This class provides methods to read characters from the underlying
character input stream.

5 InputStreamReader This class provides methods to convert bytes to characters.

6 PipedReader This class provides methods to read characters from the connected
piped output stream.

7 StringReader This class provides methods to read characters from a string.

The Reader class methods are given in the following table.

SN Method Description

1 int read() This method returns the integral representation of the next character
present in the input. It returns -1 if the end of the input is
encountered.

2 int read(char This method is used to read from the specified buffer. It returns the
total number of characters successfully read. It returns -1 if the end of

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
buffer[]) the input is encountered.

3 int read(char This method is used to read the specified nChars from the buffer at
buffer[], int loc, int the specified location. It returns the total number of characters
nChars) successfully read.

4 void mark(int This method is used to mark the current position in the input stream
nchars) until nChars characters are read.

5 void reset() This method is used to reset the input pointer to the previous set
mark.

6 long skip(long This method is used to skip the specified nChars characters from the
nChars) input stream and returns the number of characters skipped.

7 boolean ready() This method returns a boolean value true if the next request of input
is ready. Otherwise, it returns false.

8 void close() This method is used to close the input stream. However, if the
program attempts to access the input, it generates IOException.

Writer Class

Writer class is used to write 16-bit Unicode characters to the output stream. The methods
of the Writer class generate IOException. Like Reader class, Writer class is also an abstract
class that cannot be instantiated; therefore, the subclasses of the Writer class are used to
write the characters onto the output stream. The subclasses of the Writer class are given in
the below table.

SN Class Description

1 BufferedWriter This class provides methods to write characters to the buffer.

2 FileWriter This class provides methods to write characters to the file.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
3 CharArrayWriter This class provides methods to write the characters to the character
array.

4 OutpuStreamWriter This class provides methods to convert from bytes to characters.

5 PipedWriter This class provides methods to write the characters to the piped output
stream.

6 StringWriter This class provides methods to write the characters to the string.

To write the characters to the output stream, the Write class provides various methods
given in the following table.

SN Method Description

1 void write() This method is used to write the data to the output stream.

2 void write(int i) This method is used to write a single character to the output stream.

3 Void write(char This method is used to write the array of characters to the output stream.
buffer[])

4 void write(char buffer This method is used to write the nChars characters to the character array
[],int loc, int nChars) from the specified location.

5 void close () This method is used to close the output stream. However, this generates
the IOException if an attempt is made to write to the output stream after
closing the stream.

6 void flush () This method is used to flush the output stream and writes the waiting
buffered characters.

Method of InputStreamReader Class in Java


1. read(): reads a single character from the reader
2. read(char[] array): reads the characters from the reader and stores them in the
specified array
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
3. read(char[] array, int start, int length): reads the number of characters equal to
length from the reader and stores in the specified array starting from the start.
4. getEncoding(): It can be used to get the type of encoding that is used to store data
in the input stream.
5. close() : To close the input stream reader, we can use the close() method. Once the
close() method is called, we cannot use the reader to read the data.
6. ready(): checks if the stream is ready to be read
7. reset(): returns the control to the point in the stream where the mark was set

OutputStreamWriter class in java

The OutputStreamWriter class of the java.io package can be used to convert data in
character form into data in bytes form. It extends the abstract class Writer. The
OutputStreamWriter class works with other output streams. It is also known as a bridge
between byte streams and character streams. This is because the OutputStreamWriter
converts its characters into bytes.
Creating OutputStreamWriter: OutputStreamReader output = new
OutputStreamReader (file, Charset cs);
Example: Program to understand OutputStreamWriter Class
import java.io.*;

public class OSWDemo

public static void main(String[] args) {

try {

OutputStream outputStream = new FileOutputStream("output.txt");

Writer outputStreamWriter = new OutputStreamWriter(outputStream);

outputStreamWriter.write("Hello World");

outputStreamWriter.close();

System.out.println("Success");

} catch (Exception e) {

e.getMessage();

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
}

Output: Success
output.txt
Hello World
Methods of OutputStreamWriter Class in Java
1. write(): writes a single character to the writer
2. write(char[] array): writes the characters from the specified array to the writer
3. write(String data): writes the specified string to the writer
4. getEncoding(): It can be used to get the type of encoding that is used to write data
to the output stream.
5. close() : To close the output stream writer, we can use the close() method. Once the
close() method is called, we cannot use the writer to write the data.
6. flush(): forces to write all the data present in the writer to the corresponding
destination
7. append(): inserts the specified character to the current writer

FileReader Class in Java

Java FileReader class is used to read data from the file. This is a character stream class that
is used to read the file information char by char. It extends the InputStreamReader class.
Creating FileReader Class
Here is how we can create a FileReader:
Using the name of the file
Syntax : FileReader input = new FileReader(String name);
Using an Object of the file
Syntax : FileReader input = new FileReader(File fileObj);
Example: Program to understand FileReader class in Java
import java.io.*;

public class FRDemo

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

FileReader fr=new FileReader("file.txt");

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
int i;

while((i=fr.read())!=-1)

System.out.print((char)i);

fr.close();

Methods of FileReader class in Java


1. read(): reads a single character from the reader
2. read(char[] array): reads the characters from the reader and stores them in the
specified array
3. read(char[] array, int start, int length): reads the number of characters equal to
length from the reader and stores in the specified array starting from the start.
4. getEncoding(): It can be used to get the type of encoding that is used to store data
in the file.
5. close() : To close the input stream reader, we can use the close() method. Once the
close() method is called, we cannot use the reader to read the data.
6. ready(): checks if the file reader is ready to be read
7. reset(): returns the control to the point in the reader where the mark was set

FileWriter class in Java

This character stream class is used to write the content onto the file char by char. It is used
for file handling in java. It extends the OutputStreamWriter class.
Creating FileWriter object

FileWriter fw = new FileWriter(“filename”); //overwrite

FileWriter fw = new FileWriter(“filename”, true); //append

Example: Program to understand FileWriter class in Java


import java.io.*;

public class FWDemo

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
public static void main (String args[]) throws IOException

FileWriter fw = new FileWriter ("output.txt");

String str = "This time never come back";

fw.write (str);

char chars[] = str.toCharArray ();

fw.write (chars);

for (int i = 0; i < str.length (); i++)

fw.write (str.charAt (i));

fw.flush ();

fw.close ();

System.out.println ("Success");

Output: Success
Output.txt
This time never come backThis time never come backThis time never come back
Methods of FileWriter Class in Java
1. write(): writes a single character to the writer
2. write(char[] array): writes the characters from the specified array to the writer
3. write(String data): writes the specified string to the writer
4. close() : To close the file writer, we can use the close() method. Once the close()
method is called, we cannot use the writer to write the data.
5. flush(): forces to write all the data present in the writer to the corresponding
destination

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
BufferedReader class in Java

This is a character stream class which is used to perform reading operation from any input
device like keyboard, file, etc. It makes the performance fast. It inherits the Reader class.
During the read operation in BufferedReader, a chunk of characters is read from the disk
and stored in the internal buffer. And from the internal buffer characters are read
individually. Hence, the number of communication to the disk is reduced. This is why
reading characters is faster using BufferedReader.
Creating BufferedReader Object: BufferedReader buffer = new BufferedReader
(Reader obj);
Example: Program to understand BufferedReader Class
import java.io.*;

public class BRDemo

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

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

System.out.println("Enter your name");

String name = br.readLine();

System.out.println("Welcome " + name);

Output:
Enter your name
Anurag
Welcome Anurag

BufferedWriter Class in Java

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
The BufferedWriter class of the java.io package can be used with other writers to write data
(in characters) more efficiently. It extends the abstract class Writer. It makes the
performance fast. The buffering characters are used for providing the efficient writing of
single arrays, characters, and strings.
Creating BufferedWriter Object: BufferedWriter buffer = new BufferedWriter (file);
Example: Program to understand BufferedWriter Class in Java
import java.io.*;

public class BWDemo

public static void main(String[] args) throws Exception

FileWriter writer = new FileWriter("file.txt");

BufferedWriter buffer = new BufferedWriter(writer);

buffer.write("Welcome to Java Programming Language.");

buffer.close();

System.out.println("Success");

Output: Success
file.txt
Welcome to Java Programming Language.

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

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Constructor
Constructor Description

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


file, String mode) optionally to write to, the file specified by the File argument.

RandomAccessFile(String name, Creates a random access file stream to read from, and
String mode) optionally to write to, a file with the specified name.

Method
Modifier Method Method
and Type

Void close() It closes this random access file stream and releases any
system resources associated with the stream.

FileChannel getChannel() It returns the unique FileChannel object associated with


this file.

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

String readUTF() It reads in a string 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 the


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

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Void writeFloat(float v) It converts the float argument to an int using the
floatToIntBits method in class Float, and then writes that
int value to the file as a four-byte quantity, high byte first.

Void write(int b) It writes the specified byte to this file.

Int read() It reads a byte of data from this file.

Long length() It returns the length of 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.

Example

1. import java.io.IOException;
2. import java.io.RandomAccessFile;
3.
4. public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
15. throws IOException {
16. RandomAccessFile file = new RandomAccessFile(filePath, "r");
17. file.seek(position);
18. byte[] bytes = new byte[size];
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
19. file.read(bytes);
20. file.close();
21. return bytes;
22. }
23. private static void writeToFile(String filePath, String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }

The myFile.TXT contains text "This class is used for reading and writing to random access
file."

after running the program it will contains

This class is used for reading I love my country and my peoplele.

File Management

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.

Fields

Modifier Type Field Description

Static String pathSeparator It is system-dependent path-separator character, represented


as a string

for convenience.

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Static char pathSeparatorChar It is system-dependent path-separator character.

Static String separator It is system-dependent default name-separator character,


represented as a string for convenience.

Static char separatorChar It is system-dependent default name-separator character.

Constructors

Constructor Description

File(File parent, String It creates a new File instance from a parent abstract pathname and a child
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, String It creates a new File instance from a parent pathname string and a child
child) pathname string.

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

Useful Methods

Modifier Method Description


and Type

static File createTempFile(String It creates an empty file in the default temporary-file


prefix, String suffix) directory, using the given prefix and suffix to generate its
name.

Boolean createNewFile() It atomically creates a new, empty file named by this

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
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 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.

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.

Path toPath() It returns a java.nio.file.Path object constructed from the


this abstract path.

URI toURI() It constructs a file: URI that represents this abstract


pathname.

File[] listFiles() It returns an array

of abstract pathnames denoting the files in the directory

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
denoted by this abstract pathname

Long getFreeSpace() It returns the number of unallocated bytes in the partition


named by this abstract path name.

String[] list(FilenameFilter filter) It returns an array of strings naming the files and
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.

Java File Example 1

Prepard by K.Swathi Lakshmi Durga


Assistant Professor
Department of IT
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT

You might also like