X

Play AlgoQuiz

Rate Us :



Share with Friends :

Menu

File :

File is a collection of records. If we want to store the data permanently then we must choose one file. We know that the file resides in secondary memory. Every record of the file is one of the Java object. Programmatically, an object data becomes record in the file and a record of a file becomes object in Java. The File class makes it easier to write platform independent code that examines and manipulate files.


 File f = new File("file.txt");
 

This line won't create any physical file, firstly it will check is there is any file named with file.txt is available or not. If it is available then f simply points to that file but if it is not available then f represents just name of the file without creating any physical file.

Example1 :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { File f = new File("file.txt"); System.out.println(f.exists()); f.createNewFile(); System.out.println(f.exists()); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

false true

A Java file can also represent a directory.

Example2 :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { File f = new File("dir"); System.out.println(f.exists()); f.mkdir(); System.out.println(f.exists()); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

false true

Constructors for File class :


File(String name) :

This constructor creates a Java object to represent name of a file or directory.


File(String subdir , String name) :

This constructor creates a file or directory present in some other directory.


File(File subdir , String name) :

This constructor creates a file or directory present in the specified directory.


File(URI uri) :

This constructor creates a new file instance by converting the given File:URI into an abstract pathname.

Example :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { File f1 = new File("dir1"); f1.mkdir(); File f2 = new File(f1 , "file1.txt"); f2.createNewFile(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

A dir1 directory will be created in which file1.txt file will be created. These both will be stored in the same location in which Example.java is stored.

Methods in File class :


boolean exists() :-

This method is used to test whether the file or directory denoted by the abstract pathname exist or not.


boolean createNewFile() :-

Firstly, this method will check whether the specified file is already available or not. If it is already available then this method will return false without creating new file. If it is not already available then this method returns true after creating a new file.


boolean canExecute() :-

This method is used to test whether the application can execute the file denoted by the abstract pathname.


boolean canRead() :-

This method is used to test whether the application can read the file denoted by the abstract pathname.


boolean canWrite() :-

This method is used to test whether the application can modify the file denoted by the abstract pathname.


boolean isDirectory() :-

This method is used to test whether the file denoted by the abstract pathname is a directory or not.

boolean isFile() :-

This method is used to test whether the file denoted by the abstract pathname is a normal file or not.

Example :

import java.io.*; import java.util.Scanner; class Example { public static void main(String[ ] args) throws Exception { Scanner s = new Scanner(System.in); System.out.print("Input file name : "); String filename = s.next(); File f = new File(filename); if(f.exists()) { if(f.isFile()) System.out.print("It is a file."); else if(f.isDirectory()) System.out.print("It is a directory."); } else { System.out.print("File name is not found."); } } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

Input file name : dir It is a directory.

String[ ] list() :-

This method returns an array of String naming the files and directories in the directory denoted by the abstract pathname.


File[ ] listFiles() :-

This method returns an array of abstract pathnames denoting the files in the directory denoted by the abstract pathname.

Example :

import java.io.*; import java.util.Scanner; class Example { public static void main(String[ ] args) throws Exception { Scanner s = new Scanner(System.in); System.out.print("Input file name : "); String filename = s.next(); File f = new File(filename); if(f.exists()) { if(f.isDirectory()) { String list[ ] = f.list(); for(String str : list) System.out.print(str); } else System.out.print("It is not a directory."); } else { System.out.print("File name is not found."); } } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

Input file name : dir1 file1.txt

String[ ] list(FilenameFilter filter) :-

This method returns an array of String naming the files and directories in that directory denoted by the abstract pathname.


FilenameFilter :


public interface FilenameFilter

FilenameFilter is an interface. Instances of classes that implement this interface is used to filter file name. These instances are used to filter directory listing in the list method of class File and by the abstract window toolkit's file dialog component.


boolean accept(File dir , String name) :-

This method is used to test if a specified file should be included in the file list.


boolean delete() :-

This method is used to delete the file or directory denoted by the abstract pathname.

Example :

import java.io.*; import java.util.Scanner; class Example { public static void main(String[ ] args) throws Exception { Scanner s = new Scanner(System.in); System.out.print("Input file name : "); String filename = s.next(); File f = new File(filename); Algo obj = new Algo(); if(f.exists()) { if(f.isFile()) { boolean b = f.delete(); if(b == true) System.out.print("File deleted."); else System.out.print("Error in deletion."); } else System.out.print("File is a directory."); } else { System.out.print("File name is not found."); } } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

Input file name : file.txt File deleted. Here, file named as file.txt will be deleted if exists.

long length() :-

This method returns the number of characters present in the specified file.


boolean mkdir() :-

This method is used to create the directory named by the abstract pathname.


boolean mkdirs() :-

This method is used to create a directory named by the abstract pathname including any necessary but non-existent parent directories.


Character Streams :

Character Streams are those which will transfer two bytes at a time between main memory (i.e. primary memory) and secondary memory. Character streams are more effective compare to byte streams. Character stream contains two categories of classes. They are :

  • Some of the classes participating in write operation which will transfer two bytes of data from main memory (i.e. primary memory) to secondary memory.

  • Some of the classes participating in read operation and they transfer two bytes of data from secondary memory to main memory (i.e. primary memory).

All the above two categories of classes are present in java.io package.

The classes Reader , InputStreamReader , Writer and OutputStreamWriter are the predefined abstract classes present in character streams and they are reserved by Sun Microsystem developers for the future enhancements in the character streams and we won't use them directly in our program.

The classes FileReader and FileWriter are the bottommost concrete subclasses in character streams.

FileReader class functionality is more or less similar to FileInputStream class (both of them are meant for opening the file in read mode). But FileReader class objects read two bytes of data from file of secondary memory into main memory (i.e. primary memory) whereas FileInputStream class objects read one byte of data.

The functionality of FileWriter class is more or less similar to FileOutputStream class (both of them are meant for opening the file in write mode). But FileWriter class object writes two bytes of data from secondary memory to main memory (i.e. primary memory) whereas FileOutputStream class objects write one byte of data.


FileWriter :

FileWriter is a convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte buffer size are acceptable. To specify these value we need to construct an OutputStreamWriter on a FileOutputStream. It is used to create text file. We can use file writer object to write character data to the file.


Constructors for FileWriter class :


FileWriter(String file_name) :-

This constructor is used to construct a FileWriter object of the given file name.


FileWriter(File file) :-

This constructor is used to construct a FileWriter object of the given file object.


FileWriter(String file_name , boolean append) :-

If the specified file is not already available then this constructor will create that file of the given file name.


FileWriter(File file , boolean append) :-

If the specified file is not already available then this constructor will create that file of the given file object.


Methods in FileWriter class :


write(int ch) :-

This method is used to write a single character to the file.


write(char [ ] ch) :-

This method is used to write an array of characters to the file.


write(String file_name) :-

This method is used to write String to the file.


flush() :-

This method is used to give guarantee that the last character of the data also return to the file.


close() :-

This method is used to close the file.

Example1 :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileWriter fw = new FileWriter("file2.txt"); fw.write(65); fw.write("lgo\nValley"); fw.write('\n'); char[ ] ch = {'J' , 'A' , 'V' , 'A'}; fw.write(ch); fw.write('\n'); fw.flush(); fw.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

This will be stored in file2.txt : Algo Valley JAVA

Example2 :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileWriter fw = new FileWriter("file2.txt" , true); fw.write(65); fw.write("lgo\nValley"); fw.write('\n'); char[ ] ch = {'J' , 'A' , 'V' , 'A'}; fw.write(ch); fw.write('\n'); fw.flush(); fw.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

This will be stored in file2.txt : Algo Valley JAVA Algo Valley JAVA Here, file2.txt will be appended with data and store both previous data from Example1 and current data from Example2.

FileReader :

FileReader is meant for reading stream of characters. We can use FileReader to read character data from the file.


Constructors for FileReader class :


FileReader(String file_name) :-

This constructor creates a new FileReader of the given file name.


FileReader(File file) :-

This constructor creates a new FileReader of the given file object.


Methods in FileReader class :


int read() :-

This method is used to read next character from the file and return it's Unicode value.

If the next character is not available then this method will return -1.


int read(char[ ] ch) :-

This method is used to read enough characters from the file into the char[ ] array and returns the number of characters which are copied from file to the char[ ] array.


void close() :-

This method is used to close the file.

Example1 :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileReader fr = new FileReader("file2.txt"); int a = fr.read(); while(a != -1) { System.out.print((char) a); a = fr.read(); } } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

Algo Valley JAVA Algo Valley JAVA

Example2 :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { File f = new File("file2.txt"); FileReader fr = new FileReader(f); char[ ] ch = new char[(int) f.length()]; fr.read(ch); for(char c : ch) System.out.print(c); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

Algo Valley JAVA Algo Valley JAVA If the data in the file exceeds the range of int then it is not recommended to used this approach and should follow first approach i.e. Example1.

Note :

While writing data by FileWriter we have to insert line separator ('\n') manually which is a problem for programmer.

By using FileReader we can read data character by character which is not convenient for programmer.

To resolve these problem Sun Microsystem introduced BufferedWriter and BufferedReader class.


BufferedWriter :

We can used BufferedWriter to write character to the file.


Constructors for BufferedWriter class :


BufferedWriter(writer w) :-

This constructor creates a buffering character output stream that uses a default buffer size.


BufferedWriter(writer w , int buffersize) :-

This constructor creates a buffering character output stream that uses specified buffer size.


Note :

BufferedWriter never communicates directly with the file, compulsory it should communicate via some writer object only.


Methods in BufferedWriter class :


write(int ch) :-

This method is used to write single character to the file.


write(char[ ] ch) :-

This method is used to write an array of characters into the file.


write(String s) :-

This method is used to write the String to the file.


flush() :-

This method is used to give guarantee that the last character of the data also return to the file.


close() :-

This method is used to close the file.


newLine() :-

This method is used to insert a new line character.

Example :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { File f = new File("file3.txt"); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); bw.write(65); bw.write("lgo"); bw.newLine(); bw.write("Valley"); bw.newLine(); char[ ] ch = {'J' , 'A' , 'V' , 'A'}; bw.write(ch); bw.flush(); bw.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

This will be stored in file3.txt : Algo Valley JAVA Note : Whenever we are closing BufferedWriter then automatically underlying writers will be closed.

BufferedReader :

BufferedReader reads text from character input stream, buffering character so as to provide for efficient reading of character, array and lines. The main advantage of BufferedReader over FileReader is that we can read the data line by line instead of reading the data character by character. This improve the performance of the system by reducing the number of read operations.


Constructors for BufferedReader class :


BufferedReader(Reader r) :-

This constructor creates a buffering character input stream that uses default buffer size.


BufferedReader(Reader r , int buffersize) :-

This constructor creates a buffing character input stream that uses an input buffer of the specified size.


Methods in BufferedReader class :


int read() :-

This method is used to read a single character from the file.


int read(char[ ] ch) :-

This method is used to read enough character from a file to an array.


void close() :-

This method is used to close the file.


String readLine() :-

This method is used to read next line and if the next line is available then it returns that line, otherwise it returns 'null'.

Example :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileReader fr = new FileReader("file3.txt"); BufferedReader br = new BufferedReader(fr); String s = br.readLine(); while(s != null) { System.out.println(s); s = br.readLine(); } br.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

Algo Valley JAVA Note : Whenever we are closing BufferedWriter then automatically underlying writers will be closed.

PrintWriter :

PrintWriter prints formatted representation of object to a text output stream. This class implements all of the print methods found in printstream. It doesn't contain any methods for writing raw bytes. This is the most enhanced writer to write character data to a file. By using FileWriter and BufferedWriter we can write only character data but by using PrintWriter we can write any primitive data types to the file.


Constructors for PrintWriter class :


PrintWriter(String filename) :-

This constructor creates a new PrintWriter without automatic line flushing.


PrintWriter(File file) :-

This constructor creates a new PrintWriter with specified file object.


PrintWriter(writer w) :-

This constructor creates a new PrintWriter that uses a default buffer size.


Methods in PrintWriter class :


write(int ch) :-

This method is used to write single character to the file.


write(char[ ] ch) :-

This method is used to write an array of characters into the file.


write(String s) :-

This method is used to write the String to the file.


flush() :-

This method is used to give guarantee that the last character of the data also return to the file.


close() :-

This method is used to close the file.


print(char ch) :-

This method is used to write character type value to the file.


print(boolean b1) :-

This method is used to write boolean type value to the file.


print(byte b2) :-

This method is used to write byte type value to the file.


print(short s) :-

This method is used to write short type value to the file.


print(int i) :-

This method is used to write integer type value to the file.


print(long l) :-

This method is used to write long type value to the file.


print(float f) :-

This method is used to write float type value to the file.


print(double d) :-

This method is used to write double type value to the file.


print(String s) :-

This method is used to write String type value to the file.


print(char[ ] ch) :-

This method is used to write character array type value to the file.


println(char ch) :-

This method is used to write character type value to the file and the cursor goes to next line.


println(boolean b1) :-

This method is used to write boolean type value to the file and the cursor goes to next line.


println(byte b2) :-

This method is used to write byte type value to the file and the cursor goes to next line.


println(short s) :-

This method is used to write short type value to the file and the cursor goes to next line.


println(int i) :-

This method is used to write integer type value to the file and the cursor goes to next line.


println(long l) :-

This method is used to write long type value to the file and the cursor goes to next line.


println(float f) :-

This method is used to write float type value to the file and the cursor goes to next line.


println(double d) :-

This method is used to write double type value to the file and the cursor goes to next line.


println(String s) :-

This method is used to write String type value to the file and the cursor goes to next line.


println(char[ ] ch) :-

This method is used to write character array type value to the file and the cursor goes to next line.

Example :

import java.io.*; class Example { public static void main(String[ ] args) throws Exception { FileWriter fw = new FileWriter("file4.txt"); PrintWriter pw = new PrintWriter(fw); pw.write(65); pw.println(65); pw.println(true); pw.println(10.5); pw.println("Algo"); pw.println('V'); pw.flush(); pw.close(); } } //save as : Example.java //compile as : javac Example.java //run as : java Example

Output :

A65 true 10.5 Algo V Note : Whenever we are closing PrintWriter then automatically underlying writers will be closed.

Note :

The most enhanced writer to write character data is PrintWriter and the most enhanced reader to read character data is BufferedReader.



X

MiniDoll :

MiniDoll is an application to learn with fun. You can play it to solve some tricky questions related to Java Programming. Either enjoy playing it alone or discuss with your friends to solve it. It is a simple approach to learn by solving questions. This application has different topics of Java and each topic is divided into three phases. Start solving from initial topic to final topic and by the end of every topic you can boost your concept of that topic.