FILES
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.
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.
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");
System.in
System.out
System.err
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.
Byte stream
Character Stream.
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.
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.
5 FilterInputStream This class contains methods to read bytes from the other input
streams, which are used as the primary source of data.
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.
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.
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.
SN Method Description
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:
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.
{
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
public static void main (String[]args)
try
ch = fis.read ();
fis.close ();
catch (Exception e)
e.getStackTrace ();
fos.write (ch);
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.
int ch;
ch = fis.read();
while(ch!= -1) {
fos.write(ch);
ch = fis.read();
fis.close();
fos.close();
int ch;
ch = bais.read();
System.out.print((char) ch);
ch = bais.read();
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
}
try {
out.write(array);
out.close();
catch(Exception e) {
e.getStackTrace();
System.out.println("str="+str);
System.out.println("i="+i);
double d = Double.parseDouble(dis.readLine());
System.out.println("d="+d);
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.*;
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
Output: Succcess…
input.txt
A
Java BufferedInputStream class is used to read information from stream. It internally uses
buffer mechanism to make the performance fast.
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.
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 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()
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:
Constructor Description
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
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
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.
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.
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.
6 PipedReader This class provides methods to read characters from the connected
piped output stream.
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
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
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.
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.*;
try {
outputStreamWriter.write("Hello World");
outputStreamWriter.close();
System.out.println("Success");
} catch (Exception e) {
e.getMessage();
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
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.*;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
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
fw.write (str);
fw.write (chars);
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
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.*;
Output:
Enter your name
Anurag
Welcome Anurag
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.
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.
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 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."
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
for convenience.
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
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.
String getName() It returns the name of the file or directory denoted by this
abstract pathname.
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.