Ntroduction: Java - Io
Ntroduction: Java - Io
InputStream:
The InputStream class is used for reading the data such as a byte and array of
bytes from an input source. An input source can be a file, a string, or memory that
may contain the data. It is an abstract class that defines the programming interface
for all input streams that are inherited from it. An input stream is automatically
opened when you create it. You cans explicitly close a stream with
the close( ) method, or let it be closed implicitly when the object is found as a
garbage.
The subclasses inherited from the InputStream class can be seen in a hierarchy
manner shown below:
InputStream is inherited from the Object class. Each class of the InputStreams
provided by the java.io package is intended for a different purpose.
OutputStream:
The OutputStream class is a sibling to InputStream that is used for writing byte and
array of bytesto an output source. Similar to input sources, an output source can be
anything such as a file, a string, or memory containing the data. Like an input
stream, an output stream is automatically opened when you create it. You can
explicitly close an output stream with the close( ) method, or let it be closed
implicitly when the object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy
structure shown below:
OutputStream is also inherited from the Object class. Each class of the
OutputStreams provided by the java.io package is intended for a different purpose.
How Files and Streams Work:
Java uses streams to handle I/O operations through which the data is flowed from
one location to another. For example, an InputStream can flow the data from a
disk file to the internal memory and an OutputStream can flow the data from the
internal memory to a disk file. The disk-file may be a text file or a binary file. When
we work with a text file, we use a characterstream where one character is treated
as per byte on disk. When we work with a binary file, we use a binary stream.
The working process of the I/O streams can be shown in the given diagram.
Classes:
The following listing of classes are provided by the java.io package shown in the
table:
Class Description
BufferedInputStream It used for creating an internal
buffer array. It supports the mark
and reset methods.
BufferedOutputStream This class used for writes byte to
output stream. It implements a
buffered output stream.
BufferedReader This class provides read text from
character input stream and buffering
characters. It also reads characters,
arrays and lines.
BufferedWriter This class provides write text from
character output stream and
buffering characters. It also writes
characters, arrays and lines.
ByteArrayInputStream It contains the internal buffer and
read data from the stream.
ByteArrayOutputStream This class used for data is written
into byte array. This is implement in
output stream class.
CharArrayReader It used for char input stream and
implements a character buffer.
CharArrayWriter This class also implements a
character buffer and it uses an
writer.
DataInputStream This class reads the primitive data
types from the input stream in a
machine format.
DataOutputStream This class writes the primitive data
types from the output stream in
machine format.
File This class shows a file and directory
pathnames.
FileDescriptor This class uses for create a
FileInputStream and
FileOutputStream.
FileInputStream It contains the input byte from a file
and implements an input stream.
FileOutputStream It uses for writing data to a file and
also implements an output stream.
FilePermission It provides the permission to access
a file or directory.
FileReader This class used for reading
characters file.
FileWriter This class used for writing
characters files.
FilterInputStream This class overrides all methods of
InputStream and contains some
other input stream.
FilterOutputStream This class overrides all methods of
OutputStream and contains some
other output stream.
FilterReader It reads the data from the filtered
character stream.
FilterWriter It writes data from the filtered
character stream.
InputStream This class represents an input stream
of bytes.
InputStreamReader It reads bytes and decodes them into
characters.
LineNumberReader This class has a line numbers
ObjectInputStream This class used for recover the
object to serialize previously.
ObjectInputStream.GetField This class access to president fields
read form input stream.
ObjectOutputStream This class used for write the
primitive data types and also write
the object to read by the
ObjectInputStream.
ObjectOutputStream.GetFiel This class access to president fields
d write in to ObjectOutput.
ObjectStreamClass Serialization's descriptor for classes.
ObjectStreamField This class describes the serializable
field.
OutputStream This class represents an output
stream of bytes.
OutputStreamWriter It writes bytes and decodes them
into characters.
PipedInputStream In this class the data bytes are
written into piped output stream.
This class also connected into a
piped output stream.
PipedOutputStream This class also communicates the
piped input stream into piped output
stream. It creates communication
between both.
PipedReader It is a piped character-input stream.
PipedWriter It is a piped character-output stream.
PrintStream This class adds the functionality of
another output stream.
PrintWriter This class adds the functionality of
another input stream.
PushbackInputStream It also include the another function
of input stream. Such as: "push
back" or "unread" one byte.
PushbackReader This is a character stream reader and
reads the data push back into the
stream.
RandomAccessFile It supports both reading and writing
to a random access file.
Reader It used for reading character stream.
SequenceInputStream It represents the logical
concatenation of other input stream.
SerializablePermission This is a serializable permission
class.
StreamTokenizer It takes an input stream and parse it
into "tokens" . The token to be
allowed at the read time.
StringReader This is a character string class. It has
character read source.
StringWriter This is also a character string class.
It uses to shows the output in the
buffer.
Writer It uses for writing to character
stream.
Interfaces:
The following summary of Interfaces provided by the java.io package shown in the
table:
Interface Description
DataInput This interface can be used for reading byte
stream and reconstructing the java
primitive data types.
DataOutput This interface can be used for writing the
byte stream and converting data from the
java primitive data types.
Externalizable This is written in Serializable Stream. It
save and store it's contents.
FileFilter It can be used for Filtering the Pathnames.
FilenameFilter This interface used for Filter the Filenames.
ObjectInput This interface used for reading of objects
and it extends the DataInput interface.
ObjectInputValidation This is a Callback interface. It allows the
validation of objects within a graph.
ObjectOutput This interface used for writing of objects
and it extends the DataOutput interface.
This interface used for Constants writing
ObjectStreamConstant
into Serialization Objects Stream.
s
Serializable This interface implementing in the
java.io.Serializable interface.
Exceptions Classes:
The following summary of the exception classes provided by the java.io package
shown in the table:
Exceptions Description
CharConversionException It provides detail message in the
catch block to associated with the
CharConversionException
EOFException This exception indicates the end of
file. When the file input stream to
be end then EOFException to be
occuted.
FileNotFoundException When the open file's pathname
does not find then this exception
to be occured.
InterruptedIOException When the I/O operations to
interrupted from any causes then it
becomes.
InvalidClassException Any problems to be created with
class, when the Serializing
runtime to be detected.
InvalidObjectException When the de-serialized objects
failed then it occurs.
IOException When the I/O operations to be
failed then it occurs.
NotActiveException The Serialization or
deserialization operations are not
active then it occurs.
NotSerializableException This exception when the instance
is required to a Serializable
interface.
ObjectStreamException This is a supper class of all
exception class. It used for
specific to Object Stream Classes.
OptionalDataException When the reading data operations
to failed then it these exception
occurs. It is belonging to the
serialized object
StreamCorruptedException It thrown when the control
information that was read form an
object stream vioaltes internal
consistency checks.
SyncFaieldException The sync operation is failed then
SyncFaieldException to be occure.
UnsupportedEncodingExceptio The Character Encoding is not
n supported.
UTFDataFormatException A molformed UTF-8 has been
read in a data input stream, it
implemented by data input
interface.
WriteAbortedException In this exception to be thrown by
the ObjectStreamException during
a write operating.
Reading Text from the Standard Input
Standard Streams:
Standard Streams are a feature provided by many operating systems. By default,
they read input from the keyboard and write output to the display. They also support
I/O operations on files.
Java also supports three Standard Streams:
Standard Input: Accessed through System.in which is
used to read input from the keyboard.
Standard Output: Accessed through System.out which
is used to write output to be display.
Standard Error: Accessed through System.err which is
used to write error output to be display.
public class ReadStandardIO{
public static void main(String[] args) throws IOException{
InputStreamReader inp = new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(inp);
System.out.println("Enter text : ");
String str = in.readLine();
System.out.println("You entered String : ");
System.out.println(str);
}
}
Output of the Program:
C:\nisha>javac
ReadStandardIO.java
C:\nisha>java
ReadStandardIO
Enter text :
this is an Input Stream
You entered String :
this is an Input Stream
C:\nisha>
Working With File
In the previous chapter, we learned how to work with the streams. which provide a
simple model for reading and writing data. However, streams don't support all the
operations that are common with a disk file. In lesson, we will learn how to work
with a file using the non-stream file I/O.
The File class deals with the machine dependent files in a machine-independent
manner i.e. it is easier to write platform-independent code that examines and
manipulates files using the File class. This class is available in
the java.lang package.
The java.io.File is the central class that works with files and directories.
The instance of this class represents the name of a file or directory on the host file
system.
When a File object is created, the system doesn't check to the existence of a
corresponding file/directory. If the file exist, a program can examine its attributes
and perform various operations on the file, such as renaming it, deleting it, reading
from or writing to it.
The constructors of the File class are shown in the table:
Constructor Description
Create File object for default
File(path) directory (usually where program is
located).
File(dirpath,fname Create File object for directory path
) given as string.
File(dir, fname) Create File object for directory.
Thus the statement can be written as:
File f = new File("<filename>");
The methods that are used with the file object to get the attribute of
a corresponding file shown in the table.
Method Description
f.exists() Returns true if file exists.
f.isFile() Returns true if this is a normal file.
f.isDirectory() true if "f" is a directory.
f.getName() Returns name of the file or directory.
f.isHidden() Returns true if file is hidden.
f.lastModified() Returns time of last modification.
f.length() Returns number of bytes in file.
f.getPath() path name.
f.delete() Deletes the file.
Renames f to File f2. Returns true if
f.renameTo(f2)
successful.
f.createNewFile( Creates a file and may throw
) IOException.
Create a File
Introduction
Whenever the data is need to be stored, a file is used to store the data. File is a
collection of stored information that are arranged in string, rows, columns and lines
etc.
In this section, we will see how to create a file. This example takes the file name
and text data for storing to the file.
For creating a new fileFile.createNewFile( ) method is used. This method returns a
boolean value true if the file is created otherwise return false. If the mentioned file
for the specified directory is already exist then the createNewFile() method returns
the false otherwise the method creates the mentioned file and return true.
Lets see an example that checks the existence of a specified file.
import java.io.*;
public class CreateFile1{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file \"myfile.txt\" has been created
to the current directory");
}
}
}
First, this program checks, the specified file "myfile.txt" is exist or not. if it does
not exist then a new file is created with same name to the current location.
Output of the Program
C:\nisha>javac CreateFile1.java
C:\nisha>java CreateFile1
New file "myfile.txt" has been created
to the current directory
C:\nisha>
If you try to run this program again then after checking the existence of the file, it
will not be created and you will see a message as shown in the output.
C:\nisha>javac CreateFile1.java
C:\nisha>java CreateFile1
The specified file is already exist
C:\nisha>
public class PathFile{
public static void main(String[] args) throws IOExce
ption{
File f;
f=new File("example" + File.separator + "myfile.txt"
);
f.createNewFile();
System.out.println("New file \"myfile.txt\"
has been created
to the specified location");
System.out.println("The absolute path of the file
is: "
+f.getAbsolutePath());
}
}
Output of the program:
C:\nisha>javac PathFile.java
C:\nisha>java PathFile
New file "myfile.txt" has been created to
the specified location
The absolute path of the file is:
C:\nisha\example\myfile.txt
C:\nisha>
public class ConstructingFileNamePath {
public static void main(String[] args){
String filepath = File.separatorChar + "tapan"
+ File.separatorChar + "joshi";
System.out.println("The path of the file is : "
+ filepath);
}
}
FileInputstream
FileOutputStream
FileInputstream:
This class is a subclass of Inputstream class that reads bytes from a specified file
name . Theread() method of this class reads a byte or array of bytes from the file. It
returns -1 when the end-of-file has been reached. We typically use this class in
conjunction with a BufferedInputStreamand DataInputstream class to read
binary data. To read text data, this class is used with
anInputStreamReader and BufferedReader class. This class
throws FileNotFoundException, if the specified file is not exist. You can use the
constructor of this stream as:
FileInputstream(File filename);
FileOutputStream:
This class is a subclass of OutputStream that writes data to a specified file name.
The write()method of this class writes a byte or array of bytes to the file. We
typically use this class in conjunction with a BufferedOutputStream and
a DataOutputStream class to write binary data. To write text, we typically use it
with a PrintWriter, BufferedWriter and anOutputStreamWriter class. You can
use the constructor of this stream as:
FileOutputstream(File filename);
DataInputStream:
This class is a type of FilterInputStream that allows you to read binary data of Java
primitive data types in a portable way. In other words, the DataInputStream class
is used to read binary Java primitive data types in a machine-independent way. An
application uses a DataOutputStreamto write data that can later be read by a
DataInputStream. You can use the constructor of this stream as:
DataInputStream(FileOutputstream finp);
The following program demonstrate, how the contains are read from a file.
import java.io.*;
public class ReadFile{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()&& f.length()<0)
System.out.println("The specified file is not exist");
else{
FileInputStream finp=new FileInputStream(f);
byte b;
do{
b=(byte)finp.read();
System.out.print((char)b);
}
while(b!=-1);
finp.close();
}
}
}
C:\nisha>java ReadFile
This is a text file?
C:\nisha>
This program reads the bytes from file and display it to the user.
Download this Program
The another program use DataInputStreams for reading textual input line by line
with an appropriate BufferedReader.
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
C:\nisha>
public class WriteFile{
public static void main(String[] args) throws IOException{
File f=new File("textfile1.txt");
FileOutputStream fop=new FileOutputStream(f);
if(f.exists()){
String str="This data is written through the program";
fop.write(str.getBytes());
fop.flush();
fop.close();
System.out.println("The data has been written");
}
else
System.out.println("This file is not exist");
}
}
C:\nisha>java WriteFile
The data has been written
C:\nisha>
public class FileWriter{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the file name to create : ");
String file_name = in.readLine();
File file = new File(file_name);
boolean exist = file.createNewFile();
if (!exist)
{
System.out.println("File already exists.");
System.exit(0);
}
else
{
FileWriter fstream = new FileWriter(file_name);
BufferedWriter out = new BufferedWriter(fstream);
out.write(in.readLine());
out.close();
System.out.println("File created successfully.");
}
}
}
C:\nisha>java CreateFile
Please enter the file name to
create : nishu.txt
this is my name
File created successfully.
C:\nisha>
BufferedWriter
The BufferWriter class is used to write text to a character-output stream, buffering
characters so as to provide for the efficient writing of single characters, arrays, and
strings.
public class FileSize{
public static void main(String[] args) throws IOException{
System.out.print("Enter file name : ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in))
;
File f = new File(in.readLine());
if(f.exists()){
long file_size = f.length();
System.out.println("Size of the file : " + file_size);
}
else{
System.out.println("File does not exists.");
System.exit(0);
}
}
}
C:\nisha>
public class NumberOfLine{
public static void main(String[] args) {
try{
System.out.println("Getting line number of a paritcular file example!"
);
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in
));
System.out.println("Please enter file name with extension:");
String str = bf.readLine();
File file = new File(str);
if (file.exists()){
FileReader fr = new FileReader(file);
LineNumberReader ln = new LineNumberReader(fr);
int count = 0;
while (ln.readLine() != null){
count++;
}
System.out.println("Total line no: " + count);
ln.close();
}
else{
System.out.println("File does not exists!");
}
}
catch(IOException e){
e.printStackTrace();
}
}
Output of program:
C:\vinod\Math_package>javac
NumberOfLine.java
C:\vinod\Math_package>java
NumberOfLine
Getting line number of a paritcular
file example!
Please enter file name with
extension:
AddTwoBigNumbers.shtml
Total line no: 58