1. How to create a file and directory programmatically?
Constructors to create
file and directory:
=================================
File f=new File(String name);
File f=new File(String subdirname,String name);
File f=new File(File subdir,String name);
File Creation:
===========
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
File f=new File("abc.txt");
f.createNewFile();
}
}
File f=new File("abc.txt");// this line won’t create any file
f.createNewFile();//
file will be create at this line only
Directory Creation:
===============
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
File f=new File("java_programs");
f.mkdir();
}
}
Create directory and
file in a specific Directory:
========================================
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
File f=new File("E:\\programs");
f.mkdir();
File f1=new File(f,"abc.txt");
f1.createNewFile();
}
}
--------------------------------------------------------------------------------------
2. What are the FileReader and BufferedReader?
We have 2 ways to read
data from the file.
FileReader:-
=========
We can use FileReader
to read data from the file.
Constructors:-
============
FileReader fr=new FileReader(String filename);
FileReader fr=new FileReader(File f);
Methods:-
=========
int read():- by using this method we read the data character
by character. If the next character is not
available then we will
get -1. It return Unicode value, while printing we have to perform type
casting
to char.
Example:-
========
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader("ab.txt");
int i=fr.read();//to read the data
while(i!=-1){ //if next char is not available then we
will get -1
System.out.println((char)i);//perform type casting char
i=fr.read();//to read next line
}
}
}
int read(char[] ch):-it attempts to read enough characters from the
file into char[].
Example:-
========
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
File f=new File("ab.txt");
FileReader fr=new FileReader(f);
char[] ch=new char[(int)f.length()];
char[] ch=new char[(int)f.length()];//length()
to find number of char in file
fr.read(ch);//to read the data from file into char[]
for(char ch1:ch){
System.out.println(ch1);
}
}
}
In this approach
FileReader read the data character by character from the file.
BufferedReader:-
==============
To overcome FileReader
problem we use BufferedReader.
BufferedReader read the
file line by line and it can’t communicate directly with
the file, it can
communicate with some reader object.It is most enhance reader.
Constructors:-
============
BufferedReader br=new BufferedReader(Reader r);
BufferedReader br=new BufferedReader(Reader r,int buffersize);
Methods:-
=========
int read(), int
read(char[] ch),close(),String readLine()
Example:-
========
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
FileReader fr=new FileReader("ab.txt");
BufferedReader br=new BufferedReader(fr);
String line=br.readLine();//to read line
while(line!=null){//repeat until line null
System.out.println(line);
line=br.readLine();// for next line
}
br.close();
}
}
----------------------------------------------------------------------------------------
3. What are the FileWriter, BufferedWriter and
PrintWriter?
We have 3 ways to
write character data into a file.
1. FileWriter:-
===========
FileWriter
Constructors:-
====================
FileWriter fw=new FileWriter(String name);
FileWriter fw=new FileWriter(File f);
Note:- if the specified file is not already
available then this constructor will create that file.
Methods:-
=========
write(int ch):- to
write single character.
write(char[] ch):- to
write characters.
write(String s):- to
write string.
flush():-
to guaranty that total data should be written properly to the file
including last character.
close():- to close the
string.
delete():- to delete
file or directory.
Example:-
=========
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
FileWriter fw=new FileWriter("abc.txt");
fw.write(100);
fw.write(‘\n’);
fw.write("iam\ngood programmer");
fw.write(‘\n’);
char[] ch={‘a’,’b’,’c’,’d’};
fw.write(ch);
fw.flush();
fw.close();
}
}
fw.write(100) write
Unicode value of 100 is ‘d’.
If we want to add
(append) data to the file we use boolean append as shown below.
FileWriter fw=new FileWriter(String filename,boolean append);
FileWriter fw=new FileWriter("abc.txt",true);
In this approach the
line separator “\n” is varied from system to system(“\n” may not work in some
systems) so it is very difficult to the programmer.
BufferedWriter:-
=============
To overcome FileWriter
problem we use BufferedWriter to write text data in to the file.
In this we have one
extra method “newline()”:- to insert a newline.
BufferedWriter
Constructors:-
========================
BufferedWriter bw=new BufferedWriter(writer w);
BufferedWriter bw=new BufferedWriter(writer w,int buffersize);
BufferedWriter can’t
communicate directly with the file, it can communicate with some writer object
like as shown in
below.
BufferedWriter bw=new BufferedWriter(new FileWriter("abc.txt"));
BufferedWriter bw=new BufferedWriter(new BufferedWriter(new FileWriter("abc.txt")));
We can take two
BufferedWriter also.
Example:-
========
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
FileWriter fw=new FileWriter("abc.txt",true);
BufferedWriter bw=new BufferedWriter(fw);
bw.write(100);
bw.newLine();
bw.write("iam good programmer");
bw.newLine();
char[] ch={‘a’,’b’,’c’,’d’};
bw.write(ch);
bw.newLine();
bw.flush();
bw.close();
}
}
Whenever we are
closing BufferWriter automatically under line FileWriter will be close and we
not
required to close.
In this approach we
should take newline() method for every line so length of the code will be
increased.
PrintWriter:-
==========
To overcome the
BufferedWriter Problem we use PrintWriter to write any type of data into the
file.
printWriter is most
enhance writer. If file not available then I will create the file and write
data into file.
Constructors:-
============
PrintWriter pw=new PrintWriter(String filename);
PrintWriter pw=new PrintWriter(File f);
PrintWriter pw=new PrintWriter(writer w);
Methods:-
========
Here we have some more
extra methods print(char ch), print(int i), print(double d), print(String
s),
print(Boolean b).
Example:-
========
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
PrintWriter pw=new PrintWriter("ab.txt");
pw.write(100);
pw.print(100);
pw.println("iam good programmer");
pw.println(true);
char[] ch={‘a’,’b’,’c’,’d’};
pw.println(ch);
pw.println(‘e’);
pw.flush();
pw.close();
}
}
In the above program
print(100) write int value “100” but write(100) write Unicode value of ‘d’.
------------------------------------------------------------------------------------------------------
4. What are the most enhanced Writer and Reader?
The most enhanced
writer is PrintWriter and the most reader is BufferedReader.
-----------------------------------------------------------------------------------------------
5. Exapain about flush() method?
To guaranty that total
data should be written properly to the file including last character.
------------------------------------------------------------------------------------------------
6. How can we list out the files and directories
in a specific directory?
Display all file and
directories from D:\Java location:
===========================================
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
int count=0;
File f=new File("D:\\Java");
String[] s=f.list();
for(String s1:s)
{
count++;
System.out.println(s1);
}
System.out.println(count);
}
}
Display files only:
==============
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws IOException
{
int count=0;
File f=new File("D:\\Java");
String[] s=f.list();
for(String s1:s)
{
File f1=new File(f,s1);
if(f1.isFile()){
count++;
System.out.println(s1);
}
}
System.out.println(count);
}
}
Display Directories
only:
====================
Just change the if
condition if(f1.isDirectory()).
--------------------------------------------------------------------------------------------------
7. What is the difference between write(100) and
print(100) of PrintWriter class?
In the case of
write(100) the corresponding character ‘d’ will be written in to the file where
as print(100) is written int value ‘100’.
-------------------------------------------------------------------------------------------------------
8. What is the difference between Reader Writer
and input output streams?
Generally we use
Reader and Writer to handle data where as we can use streams to handle binary
data(like images, videos files, audio files ect.).
We use
FileOutPutStream to write binary data to the file where as we use
FileInputStream to read binary data from the file.