Saturday, February 20, 2016

File IO in java with Examples

In this Post we will discuss Java IO(input/output) API that comes with Java. That means which is reading and writing data(Input and Output).Generally,to readdata from a file or over network and write to a file or write a response back over the network.These Input and output are located in the package java.io.


The following is the list methods going to cover in File I/O Concept.

1) File
2 )FileWriter
3) FileReader
4) BufferedWriter
5 )BufferedReader
6) printWriter


File

A java file object represent just name of the file/directory.

File f = new File(“abc.txt”);
If ‘abc.txt’ is already available then ‘f’ will represent that physical file.
If it is not already available, It won’t create any new file and ‘f’ simply represents the name of the file.

Ex:

import java.io.*;
class test
{
public static void main(String[] args)
{
File f = new File("cba.txt");
System.out.println(f.exists()); // false at first time.
f.createNewFile();
System.out.println(f.exists()); //true
}
}

I Run:

false
true

II Run:
true

true

A java file Object can represent directories also

Ex:

File f = new File("bbc");
System.out.println(f.exists());
f.mkdir();
System.out.println(f.exists());

I Run:
false
true

II Run:
true

true

The constructors of the file class

1) File f = new File(String name)
Here name may be file or directory name.
Creates a java file object that represents a file or directory name.

2) File f = new File(String subdirec, String name)
Creates a java file object that represents file or directory name present in specified
subdirectory.

3) File f = new File(File subdir, String name)

Important methods of File Class

1) boolean exists():
returns true if the physical file/directory presents other wise false.

2) boolean createNewFile():
returns ture if it creates a new file, if the required file is already available then
it won’t create any new file and returns false.

3) booelan mkdir()
For creation of directory.

4) boolean isFile():
returns true if the java file object represents a file.

5) boolean isDirectory():
returns true if the java file object represents a directory.

6) String [] list():
returns the names of files and directories present in the directories represented
by the file object.
If the java file object represents a file instead of directory this method returns
null.


7) Boolean delete():

for deleting the file or directory represented by java file object.

Write a program to create a directory ‘lucky87’ in the current working directory and create a file ‘file1.txt’ in that directory.

File f = new File(“lucky87”);
f.mkdir();
// File f1 = new File(“lucky87”,”file1.txt”);
File f1 = new File(f,”file1.txt”);
F1.createNewFile();

Write a program to list the names of files and directories in ‘jdk’ directory.

File f = new File(“jdk”);
String [] s = f.list();
for(String s1: s)
{
System.out.println(s1);

}

FileWriter:

This class can be used for writing character data to the file.

Constructors

1) FileWriter fw = new FileWriter(String fname)
2) FileWriter fw = new FileWriter(File f);

The above 2 constructors creates a file object to write character data to the file.
If the file already contains some data it will overwrite with the new data.
Instead of overriding if u have to perform append then we have to use the following constructors.

FileWriter fw = new FileWriter(String name, boolean append);
FileWriter fw = new FileWriter(File f, boolean append);

If the underlying physical file is not already available then the above constructors will create the required file also.

Important methods of FileWriter Class

1) void write(int ch) throws IOException
for writing single character to the file.
2) void write(String s)throws IOException.
3) void write(char [] ch) throws IOException.
4) void flush():-To guaranteed that the last character of the data should be required to the file.

Ex:-

class test
{
public static void main(String arg[])throws Exception
{
File f = new File("pongal.txt");
System.out.println(f.exists());
FileWriter fw = new FileWriter(f,true);
System.out.println(f.exists());
fw.write(97);
fw.write("run\nsoftware\n");
char [] ch1 = {'a','b','c'};
fw.write(ch1);
fw.flush();
fw.close();
}
}

FileReader

This class can be used for reading character data from the file.
Constructors

1) FileReader fr = new FileReader(String name);
2) FileReader fr = new FileReader(File f);

Important methods of FileReader Class

1) int read():
for reading next character from the file. If there is no next character this method
returns -1

2) int read(char[] ch):
to read data from the file into char array.

3) void close():
to close FileReader

Ex:

class test
{
public static void main(String arg[])throws Exception
{
File f = new File("pongal.txt");
FileReader fr = new FileReader(f);
System.out.println(fr.read());
char [] ch2 = new char[(int) (f.length())];
System.out.println(ch2.length);
fr.read(ch2);
for(char ch1: ch2)
{
System.out.print(ch1);
}
}
}

The usage of FileReader and FileWriter is in efficient because
---> While writing the data by using FileWriter, program is responsible to insert line separators manually.
----> We can read the data character by character only by using FileReader. If increases the number of I/O
operations and effect performance.
To overcome these problems sun people has introduced BufferedReader and BufferedWriter classes.





BufferedWriter

This can be used for writing character data to the file.
Constructors

1) BufferedWriter bw = new BufferedWriter(writer w)
2) BufferedWriter bw = new BufferedWriter(writer r, int size)

BufferedWriter never communicates directly with the file. It should Communicate through some writer object only.

Q) Which of the following are valid declarations

1) BufferedWriter bw = new BufferedWriter(“abc.txt”); X
2) BufferedWriter bw = new BufferedWriter(new File(“abc.txt”)); X
3) BufferedWriter bw = new BufferedWriter(new FileWriter(“abc.txt”));
4) BufferedWriter bw = new BufferedWriter(new BufferedWriter(new
FileWriter(“abc.txt”)));


Important methods of BufferedWriter Class

1) void write(int ch) thorows IOException
2) void write(String s) throws IOException
3) void write(char[] ch) throws IOException
4) void newLine()
for inserting a new line character.
5) void flush()
6) void close()

Which method is available in BufferedWriter and not available in FileWriter

Ans: newLine() method


Ex:-

class test
{
public static void main(String arg[])throws Exception
{
File f = new File("pongal.txt");
System.out.println(f.exists());
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(97);
bw.newLine();
char [] ch1 = {'a','b','c','d'};
bw.write(ch1);
bw.newLine();
bw.write("raju");
bw.newLine();
bw.write("software");
bw.flush();
bw.close();
}
}

Note:- 
When ever we r closing BufferedWriter ,automatically underlying FileWriter object will be closed.

BufferedReader

By using this class we can read character data from the file.
Constructors

1) BufferedReader br = new BufferedReader(Reader r)
2) BufferedReader br = new BufferedReader(Reader r, int buffersize)

BufferedReader never communicates directly with the file. It should Communicate through some reader object only.

Important methods of BufferedReader Class

BufferedWriter
FileWriter

1) int read()
2) int read(char [] ch)
3) String readLine();

Reads the next line present in the file. If there is no nextline this method returns null.

4) void close()

Ex:

class test
{
public static void main(String arg[])throws Exception
{
FileReader fr = new FileReader("pongal.txt");
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
while(s != null)
{
System.out.println(s);
s = br.readLine();
}
br.close();
}
}

Note:-
When ever we r closing BufferedReader ,automatically underlying FileReader object will be closed.

PrintWriter

The most enhanced writer for writing character data to the file is PrintWriter()
Constructors

1) PrintWriter pw = new PrintWriter(String fname)
2) PrintWriter pw = new PrintWriter(File f);
3) PrintWriter pw = new PrintWriter(Writer w);

Important methods

1) write(int ch)
2) write(char [] ch)
3) write(String s)
4) print(int i)
print(double d)
print(char ch)
print(Boolean b)
print(char ch[])
5) void flush()
6) close()

Ex:

class test
{
public static void main(String arg[])throws Exception
{
FileWriter fw = new FileWriter("pongal.txt");
PrintWriter out = new PrintWriter(fw);
out.write(97);
out.println(100);
out.println(true);
out.println('c');
out.println("FDGH");
out.flush();
out.close();
}
}

I hope you enjoy this post and share this to your friends and also in social websites,keep follow me for latest updates.

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...