Java IO
Java IO
The Java I/O means Java Input/Output. It is provided by the java.io package. This
package has an InputStream and OutputStream. Java InputStream is defined for reading
the stream, byte stream and array of byte stream.
2. Classes and Interfaces of the I/O Streams
The following listing of classes provided by the java.io package shown in the given table.
3. Reading Text from the Standard Input
Java provides the standard I/O facilities for reading text through either from the file or
from the keyboard on command line. This program illustrates how to use standard input
to read the user input.
4. Working With the Files
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.
o Create a File
o Constructing a File Name path
o Read the File
o Write to a File
o Appending to a File
o Getting the Size of a File
o Count lines of a particular file
o Renaming a File or Directory
o Copying a File to Another File
o Copying Multiple Files
o Moving a File or Directory to Another Directory
o Deleting a File or Directory
o Change a File timestamp
o Create a Temp File
o Delete a Temp File
o Getting an absolute path and Parents of a Filename
o Creating a Directory
o Copying a Directory or file
o Traversing files and directories
o Getting the Current Working Directory
o Getting the Modification Time of a File or Directory
o Listing Files or Subdirectories
o Deleting a File
6. Filter I/O Streams
Like I/O streams, Filter streams are also used to manipulate the data reading from an
underlying stream.. Apart from this, it allows the user to make a chain using multiple
input stream so that, the operations that are to be applied on this chain, may create a
combine effects on several filters.
o Introduction
o Write to a file
o Read the file
o Another Streams
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
bytes to 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
character stream 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.
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.
These objects are defined automatically and do not need to be opened explicitly. Standard
Output and Standard Error, both are to write output; having error output separately so that
the user may read error messages efficiently.
System.in is a byte stream that has no character stream features. To use Standard Input as a
character stream, wrap System.in within the InputStreamReader as an argument.
InputStreamReader inp = new InputStreamReader(system.in);
Working with Reader classes:
Java provides the standard I/O facilities for reading text from either the file or the keyboard on
the command line. The Reader class is used for this purpose that is available in the java.io
package. It acts as an abstract class for reading character streams. The only methods that a
subclass must implement are read(char[], int, int) and close(). the Reader class is further
categorized into the subclasses.
The following diagram shows a class-hierarchy of the java.io.Reader class.
However, most subclasses override some of the methods in order to provide higher efficiency,
additional functionality, or both.
InputStreamReader:
An InputStreamReader is a bridge from byte streams to character streams i.e. it reads bytes
and decodes them into Unicode characters according to a particular platform. Thus, this class
reads characters from a byte input stream. When you create an InputStreamReader, you
specify an InputStream from which, the InputStreamReader reads the bytes.
The syntax of InputStreamReader is written as:
InputStreamReader <variable_name> = new InputStreamReader(system.in)
BufferedReader :
The BufferedReader class is the subclass of the Reader class. It reads character-input stream
data from a memory area known as a buffer maintains state. The buffer size may be
specified, or the default size may be used that is large enough for text reading purposes.
BufferedReader converts an unbuffered stream into a buffered stream using the wrapping
expression, where the unbuffered stream object is passed to the constructor for a buffered
stream class.
For example the constructors of the BufferedReader class shown as:
BufferedReader(Reader in):Creates a buffering character-input
stream that uses a default-sized input buffer.
BufferedReader(Reader in, int sz): Creates a buffering character-
input stream that uses an input buffer of the specified size.
BufferedReader class provides some standard methods to perform specific reading operations
shown in the table. All methods throws an IOException, if an I/O error occurs.
Return
Method Description
Type
read( ) int Reads a single character
read(char[] cbuf, Read characters into a portion of
int
int off, int len) an array.
Read a line of text. A line is
readLine( ) String considered to be terminated by
('\n').
close( ) void Closes the opened stream.
This program illustrates you how to use standard input stream to read the user input..
import java.io.*;
public class ReadStandardIO{
public static void main(String[] args) throws IOException{
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>
Download this example
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 file File.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>
Constructing a File Name path
In Java, it is possible to set dynamic path, which is helpful for mapping local file name with
the actual path of the file using the constructing filename path technique.
As you have seen, how a file is created to the current directory where the program is run. Now
we will see how the same program constructs a File object from a more complicated file
name, using the static constant File.separator or File.separatorCharto specify the file name
in a platform-independent way. If we are using Windows platform then the value of this
separator is ' \ ' .
Lets see an example to create a file to the specified location.
import java.io.*;
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());
}
}
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>
Download this Program
Another program set the dynamic path using File.separator given below:
import java.io.*;
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 . The
read() 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
BufferedInputStream and DataInputstream class to read binary data. To read text data,
this class is used with an InputStreamReader 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
an OutputStreamWriter 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
DataOutputStream to 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>
Download the code
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>
In this section, you will learn how to count the availability of text lines in the particular file. A
file is read before counting lines of a particular file, . File is a collection of stored information
that are arranged in string, rows, columns and lines etc. Try it for getting the lines through the
following program.
Description of program:
The following program helps you in counting lines of a particular file. At the execution time
of this program, it takes a file name with its extension from a particular directory and checks it
using the exists() method. If the file exists, it will count lines of a particular file otherwise it
will display a message "File does not exists!".
Description of code:
FileReader(File file):
This is the constructor of FileReader class that is reliable for reading a character files. It
constructs a new FileReader and takes a file name that have to be read.
FileNumberReader():
This is the constructor of FileNumberReader class. It constructs a new line-numbering
reader. It reads characters and puts into buffer. By default the numbering of line begins from
'0'.
Here is the code of program:
import java.io.*;
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
import java.text.*;
public class ChangeFileDate{
public static void main(String[] args) {
try{
System.out.println("Change file timestamp example!");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))
;
System.out.println("Enter file name with extension:");
String str = bf.readLine();
System.out.println("Enter last modified date in 'dd-mm-yyyy' format:");
String strDate = bf.readLine();
SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(strDate);
File file = new File(str);
if (file.exists()){
file.setLastModified(date.getTime());
System.out.println("Modification is successfully!");
}
else{
System.out.println("File does not exists!");
}
}
catch(Exception e){
e.printStackTrace();
}
}
Output of program:
C:\vinod\Math_package>javac
ChangeFileDate.java
C:\vinod\Math_package>java
ChangeFileDate
Change file timestamp example!
Enter file name with extension:
StrStartWith.shtml
Enter last modified date in 'dd-mm-
yyyy' format:
23-04-2007
Modification is successfully!
as the name suggest "temp". When the application is shut down, all temporary files are first
closed and then deleted.
Description of program:
The following code of program will help you in creating a Temporary File to your default
directory. Here we have created a temporary file object. Then we have used a method to get
the entire path of the temp file which gets created. The method is
tempFile.getAbsolutePath();. We have also used a try and catch block here to catch the
exception on occurrence. And if the file could not be created then we will get a message that
"temp file not created".
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class CTFile {
public static void main(String[] args){
File tempFile = null;
try {
tempFile = File.createTempFile("MyFile.txt", ".tmp"
System.out.print("Created temporary file with name
System.out.println(tempFile.getAbsolutePath());
} catch (IOException ex) {
System.err.println("Cannot create temp file: "
} finally {
if (tempFile != null) {
}
}
}
}
C:\unique>java CTFile
Created temporary file with name
C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\MyFile.txt49
754.tmp
C:\unique>
Download this example.
Output of program:
C:\vinod\Math_package>javac
DeleteTempFile.java
C:\vinod\Math_package>java
DeleteTempFile
Delete temp file example!
Please enter file name that has
'.temp' extension:
rose
file is deleted!
Download this Program:
public class GetAbsolutePath{
public static void main(String[]
args){
String str = args[0];
File file = new File(str);
String absolutePathOfFirstFile
= file.getAbsolutePath();
System.out.println(" The absol
ute path in first form is "
+ absolutePathOfFirstFile);
file = new File( "chandan" + File.
separatorChar+ str);
String absolutePathOfSecondFil
e = file.getAbsolutePath();
System.out.println(" The absol
ute path is " + absolutePathOfSeco
ndFile);
file = new File("chandan" + File.s
eparator + ".." + File.separator +
str);
String absolutePathOfThirdFile
= file.getAbsolutePath();
System.out.println(" The absol
ute path is " + absolutePathOfThir
dFile);
}
}
public class GetParentDir{
private static void dirlist(String fname){
File dir = new File(fname);
String parentpath = dir.getParent();
System.out.println("Current Directory : "+ dir);
System.out.println("parent Directory : "+ parentpath);
}
public static void main(String[] args){
String currentdir = System.getProperty("user.dir");
dirlist(currentdir);
}
C:\nisha>java
GetParentDir
Current Directory :
C:\nisha
parent Directory : C:\
C:\nisha>
Download this example.
o Creating a Directory
o Copying a Directory or file
o Traversing files and directories
o Getting the Current Working Directory
o Getting the Modification Time of a File or Directory
o Listing Files or Subdirectories
o Deleting a File
Creating a Directory
Introduction
In the section, you will learn how a directory or subdirectories are created. This program also
explains the process of creating all non-existent ancestor directories automatically. We will
use the File class to crate the directory.
File
The File class an abstract representation of file and directory pathnames. File class is used to
interact with the files system.
Here is the code for creating directory and all non-existing ancestor directories:
import java.io.*;
class CreateDirectory
{
public static void main(String args[])
{
try{
String strDirectoy ="test";
String strManyDirectories="dir1/dir2/dir3";
// Create one directory
boolean success = (new File(strDirectoy)).mkdir();
if (success) {
System.out.println("Directory: " + strDirectoy + " created");
}
// Create multiple directories
success = (new File(strManyDirectories)).mkdirs();
if (success) {
System.out.println("Directories: " + strManyDirectories + " created");
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
C:\nisha>java
CreateDirectory
Directory: test created
Directories:
dir1/dir2/dir3 created
C:\nisha>
This program takes inputs to create a directory "test" and subdirectories "dir1\dir2\dir3". the
mkdir( ) method is used to create a single directory while the mkdirs( ) method is used to
create multiple subdirectories.
Download the code
The copyDirectory() method is used to copy contents from the specified source directory to
the specified destination directory. This method takes two File type arguments passed by the
calling method in the main method and check whether the specified directory is a directory
exactly or not. If the specified name is in the exact directory format and that exists then the
method generates the list of all the sub directories and file inside the source directory using the
list() method and copy one by one to the destination directory otherwise the specified name is
copies (treated) as a file name directly.
And another method is the main method in which the program read the source and destination
directory or file name.
Here is the code of the program :
import java.io.*;
public class CopyDirectory{
public static void main(String[] args) throws IOException{
CopyDirectory cd = new CopyDirectory();
BufferedReader in = new BufferedReader
(new InputStreamReader(System.in));
System.out.println("Enter the source directory or file name : ");
String source = in.readLine();
File src = new File(source);
System.out.println("Enter the destination
directory or file name : ");
String destination = in.readLine();
File dst = new File(destination);
cd.copyDirectory(src, dst);
}
public void copyDirectory(File srcPath, File dstPath)
throws IOException{
if (srcPath.isDirectory()){
if (!dstPath.exists()){
dstPath.mkdir();
}
String files[] = srcPath.list();
for(int i = 0; i < files.length; i++){
copyDirectory(new File(srcPath, files[i]),
new File(dstPath, files[i]));
}
}
else{
if(!srcPath.exists()){
System.out.println("File or directory does not exist.");
System.exit(0);
}
else
{
InputStream in = new FileInputStream(srcPath);
OutputStream out = new FileOutputStream(dstPath);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
System.out.println("Directory copied.");
}
This section you will learn how the files and subdirectories are traversed lying under a
directory. We can find that, how many files and directories are available within a directory.
This is very frequently used where lot of work depends on the files and directories. .
The given program describes how you can traverse a directory if it contains directory and files
under it. If the directory contains no files and directory then it will tell you that the directory
contains no directory and files in it, if it contains a directory and files in it then it will display
all the files and directories.
To implement this program, first make a class named as TraversingFileAndDirectories then
make an object of File class and pass any directory and filename to its constructor. After that,
check it whether the file or directory you have entered is a directory or a file. If it is a directory
then it will display that it is a directory otherwise not a directory. If it is a directory, it checks
whether it contains more directory and files in it. If it contains then it will display you the list
of the files and directories.
Code of the program is given below
import java.io.*;
public class TraversingFileAndDirectories{
public static void main(String args[]){
String dirname = args[0];
File file = new File(dirname);
if(file.isDirectory()){
System.out.println("Directory is " + dirname);
String str[] = file.list();
for( int i = 0; i<str.length; i++){
File f=new File(dirname + " / " + str[i]);
if(f.isDirectory()){
System.out.println(str[i] + " is a directory");
}
else{
System.out.println(str[i] + " is a file");
}
}
}
else{
System.out.println(dirname + " is not a directory");
}
}
}
C:\java>java
TraversingFileAndDirectories
chandan
Directory is chandan
ConstructingFileNamePath.java is a
file
constructingfilenamepath.shtml is a
file
EnterValuesFromKeyboard.java is a
file
entervaluesfromkeyboard.shtml is a
file
Factorial.java is a file
factorial.shtml is a file
UseOfThisOperator.java is a file
useofthisoperator.shtml is a file
Download this program
This is the getProperty() method of the System class of the java.lang package returns the
system properties according to the indicated argument. Here, the mentioned indicated
argument is "user.dir" which indicates about the getting the current directory name.
Here is the code of the program :
import java.io.*;
public class GetCurrentDir{
private static void dirlist(String fname){
File dir = new File(fname);
System.out.println("Current Working Directory : "+ dir);
}
public static void main(String[] args){
String currentdir = System.getProperty("user.dir");
dirlist(currentdir);
}
}
C:\nisha>javac
GetCurrentDir.java
C:\nisha>java
GetCurrentDir
Current Working
Directory : C:\nisha
C:\nisha>
Download this example.
C:\nisha>
Download this example.
Explanation
This program list the file of the specified directory. We will be declaring a function called
dirlist which lists the contents present in the specified directory.
dirlist(String fname)
The function dirlist(String fname) takes directory name as parameter. The function creates a
new File instance for the directory name passed as parameter
File dir = new File(fname);
and retrieves the list of all the files and folders present in the directory by calling list() method
on it.
String[] chld = dir.list();
Then it prints the name of files and folders present in the directory.
Code of the Program :
import java.io.*;
public class DirListing{
private static void dirlist(String fname){
File dir = new File(fname);
String[] chld = dir.list();
if(chld == null){
System.out.println("Specified directory does not exist or is not a direc
tory.");
System.exit(0);
}else{
for(int i = 0; i < chld.length; i++){
String fileName = chld[i];
System.out.println(fileName);
}
}
}
public static void main(String[] args){
switch(args.length){
case 0: System.out.println("Directory has not mentioned.");
System.exit(0);
case 1: dirlist(args[0]);
System.exit(0);
default : System.out.println("Multiple files are not allow.");
System.exit(0);
}
}
}
C:\nisha>
At the time of execution, we have specified a directory name "example" that contains only a
single file "myfile.txt".
Download this example Example
Deleting a File
In this section, you will learn how a specified file or directory is deleted. For deleting a file
from a directory you need to give the file name to be deleted.
Description of program:
The following code of program deletes a file from a directory. In this program the compiler
will ask to enter the name of the file to be deleted. For this we have used
"BufferedReader(new InputStreamReader(System.in));" method as you very well know
about it. If the file exists in the directory then it will be deleted otherwise we will get a
message that "file was not successfully deleted".
import java.io.File;
import java.io.*;
public class DeletingFile {
public static void main(String args[])throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(
System.out.print("Enter the file name to delete:");
String file_name = in.readLine();
File file = new File("File already exist!");
boolean exist = file.createNewFile();
if (!exist){
System.out.println("File was successfully deleted.\n");
} else {
System.out.println("File was not successfully deleted.\n"
}
}
}
C:\unique>java DeletingFile
Enter the file name to delete:wonderful.txt
File was successfully deleted.
C:\unique>
Download this example.
Filter I/O Streams
Like I/O streams, Filter streams are also used to manipulate the data reading from an underlying
stream.. Apart from this, it allows the user to make a chain using multiple input stream so that, the
operations that are to be applied on this chain, may create a combine effects on several filters.
Introduction
Introduction:
As mentioned earlier, The InputStream and OutputStream classes are used for reading
from and writing to byte streams, respectively. In this section, you are going to learn of data
transforming and manipulating using Filter Streams.
Like I/O streams, Filter streams are also used to manipulate data reading from an underlying
stream. Apart from this, it allows the user to make a chain using multiple input stream so that,
the operations that are to be applied on this chain, may create a combine effects on several
filters. By using these streams, there is no need to convert the data from byte to char while
writing to a file. These are the more powerful streams than the other streams of Java.
The class hierarchy of the Filter streams derived from I/O streams can be shown as:
There are two streams, that are derived from the I/O stream class:
FilterInputStream
FilterOutputstream
FilterInputStream:
FilterInputStream is the base class for all the input stream filters and is obtained from the
InputStream class. It simply overrides all the methods of the InputStream class required to
filter data. These methods performs some sort of filtering operations on the data and cannot be
instantiated directly. It provides the additional and chaining functionality for the multiple input
streams to be filtered.
The constructor of the FilterInputStream is written as:
FilterInputStream fis = new
FilterInputStream(Inputstream in);
FilterOutputstream:
FilterOutputStream is the super class of all the output stream filters and is obtained from the
OutputStream class. It simply overrides all the methods of the OutputStream class required
to filter the data that is written to the output stream.
FilterIntputStream and FilterOutputStream do not perform any filtering themselves; this is
done by their subclasses. To improve the performance of these I/O streams, their subclasses
BufferedInputStream and BufferedOutputStream are used.
BufferedInputStream:
This class is a subclass of the FilterInputstream class that lets you read large amount of data
from a stream and store it in an internal buffer. When data is requested, it is usually read from
the buffer. This has the effect for improving the performance of some input streams, especially
for those, that are bounded to slower sources like a file or network connection.
The constructor of the BufferedInputStream is written as:
BufferedInputStream (java.io.InputStream in);
BufferedOutputStream:
This is a subclass of the BufferedOutputStream and a buffered output stream that lets you
write characters to a stream. A BufferedOutputStream adds functionality to another output
stream. The data is first written into a buffer. When the BufferedOutputStream is created, an
internal buffer array is also created, in which the bytes are stored.
The constructor of the BufferedOutputStream is written as:
BufferedOutputStream (java.io.OutputStream out);
Write to a file
As we have read about the BufferedOutputStream class that store the data in an internal
buffer and lets you write characters to a stream. Lets see an example that writes the text "Hello
Java" to the existed file.
The given example uses the BufferedOutputstream class that writes the bytes to the output
stream. The output stream is a file "Filterfile.txt" in which the data is written in form of a
byte. The getBytes( ) method of the String class returns the bytes from the string.
import java.io.*;
class WriteFilter
{
public static void main(String args[])
{
String str="Hello Java";
try
{
FileOutputStream fos = new FileOutputStream("Filterfile.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
// Now write to the buffered stream.
bos.write(str.getBytes());
bos.flush();
System.out.print("the data has been written");
}
catch (Exception e)
{
System.err.println("Error writing to a file: " + e);
}
}
}
Output of the Program:
C:\nisha>javac
WriteFilter.java
C:\nisha>java
WriteFilter
the data has been
written
C:\nisha>
Download this Program
As we have read about the BufferedInputStream class that lets you read characters from a
stream and stores it in an internal buffer. Lets see an example that reads the contains of the
existed file.
The given example uses the BufferedInputstream class that reads the bytes from the input
stream. The input stream is a file "Filterfile.txt" from which the data is read in form of a byte
through the read( ) method. The read( ) method reads the byte from the file that is converted
into the character-form.
import java.io.*;
class ReadFilter
{
public static void main(String args[])
{
try
{
FileInputStream fin = new FileInputStream("Filterfile.txt");
BufferedInputStream bis = new BufferedInputStream(fin);
// Now read the buffered stream.
while (bis.available() > 0)
{
System.out.print((char)bis.read());
}
}
catch (Exception e)
{
System.err.println("Error reading file: " + e);
}
}
}
Output of the Program:
C:\nisha>javac
ReadFilter.java
C:\nisha>java
ReadFilter
This is a text file
C:\nisha>
Download this Program
Another Streams
Introduction
The Filter File Java example code provides the following functionalities:
Filtering the files depending on the file extension provided by the user
User provides the file extension and then program lists all the matching files found
Program accepts directory name and file extension from user and displays the files present in
the directory.
Program begins with import statement java.io.*; package, which is required for any
input/output operations.
Classes Defined in the program:
OnlyExt
The constructor of the class takes file extension as parameter and then prefix it with "*." and
assign into the global variable ext. The OnlyExt class implements FilenameFilter interface, so
we have to implement the abstract method accept( ) defined in the FilenameFilter interface.
The accept( ) method tests if a specified file should be included in a file list.
FilterFiles:
The FilterFiles contains the public static void main(String args[]), which is the
entry point of our program. The program first accepts directory name and file extension from
the user and creates the object of OnlyExt class passing file extension as constructor
parameter.
Here is the code of the program :
import java.io.*;
class OnlyExt implements FilenameFilter{
String ext;
public OnlyExt(String ext){
this.ext="." + ext;
}
public boolean accept(File dir,String name){
return name.endsWith(ext);
}
}
public class FilterFiles{
public static void main(String args[]) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in))
;
System.out.println("Please enter the directory name : ");
String dir = in.readLine();
System.out.println("Please enter file type : ");
String extn = in.readLine();
File f = new File(dir);
FilenameFilter ff = new OnlyExt(extn);
String s[] = f.list(ff);
for (int i = 0; i < s.length; i++){
System.out.println(s[i]);
}
}