File Handling:File handling means performing various functions on a file, like reading, writing, editing, etc. Java provides us with a provision to perform these operations through programming, without actually having to open the file. In this article, we will take a look at all those properties of java programming and how to perform these operations using Java.
Java File Handling:
Java provides us with library classes and various methods to perform file handling easily. All these methods are present in the File Class of the java.io package.
So, first of all, before starting these programs, we need to import this package and the file class.
Java uses stream to perform file-related operations. Let us understand the concept of stream first.
Stream in Java:
Stream is a concept of java that pipelines a sequence of objects to obtain the desired result. A stream can not be called to be a data structure, rather it just takes input from the collection of I/O.
A stream can be classified into two types: Byte Stream and Character Stream.
Byte Stream:
The byte stream deals with mainly byte data. We know that one byte is equal to eight-bit. Thus, this stream mainly deals with 8bit of data. This stream performs an Input-output operation per 8bit of data.
The byte stream contains two stream classes, Input Stream classes and Output Stream Classes.
1. Input Stream Classes: This stream helps take input(Read Data) from the collection in I/O File.
2. Output Stream Classes: This stream helps to give output(Write Data) into the collection in I/O File.
The most commonly used Input and Output Stream Classes are FileInputStream and FileOutputStream.
We will see how to use them later while discussing the various file operations.
Character Stream:
There is also Character Stream which allows I/O operation on 16bit of Unicode data at a time. Character Stream takes 2 bytes of data at a time. It is faster as it can take double the intake as compared to a byte stream. Character streams usually use Byte Stream classes to implement operations.
The two main classes used in Character Stream are FileReader and FileWriter.
We will see how to use them later while discussing the various file operations.
The methods present in File class(java.io.File):
The file class contains various methods that perform various important tasks. Let us discuss them through this easy to comprehend table.
SL. No. | Method | Return Type | Description |
1. | canRead() | Boolean | This method checks whether the file is readable or not. |
2. | createNewFile() | Boolean | This method creates a new file in the desired path. The file created is generally empty. |
3. | canWrite() | Boolean | This method checks whether the file is writable or not,i.e, not a read-only file. |
4. | exists() | Boolean | This method verifies if the file asked for is present or not in the directory. |
5. | delete() | Boolean | This method is used to delete a file from the directory. |
6. | getName() | String | This method helps us find the name of a particular file from the directory. |
7. | getAbsolutePath() | String | This method returns the absolute path of the given file. |
8. | length() | Long | This method returns the size of a file in bytes. |
9. | list() | String[] | This method returns an array, listing all the files present in the present working directory(PWD). |
10. | mkdir() | Boolean | This Method stands for make directory. This method helps us create a new directory(Not a file). |
Now we will discuss the different operations for File Handling in Java using both byte stream and character stream.
Java File Operation:
1. Creating a File in Java:
We can use the createNewFile() method to create a new file using Java. If the method returns true, the file has been created successfully, else the file creation was unsuccessful.
Code to explain the working of createNewFile():
The output of the above code:
The File named NewFile.txt was created in the given path. The Try-Catch block is used to handle errors if there is already a file with the same name.
2. Java Get File Information:
Through the various methods given in File class, we are able to get all sorts of information about a file. These methods can give information like name, length, path, read-only, write-only, etc.
Code to Explain Methods to get various file information:
The output of the above code:
The absolute path of the file is: G:\Internship\File Handling\NewFile.txt
Is file writeable: true
Is file readable: true
The size of the file is: 0
The above class uses methods like getName(), getAbsolutePath(), canWrite(),canRead(),length(), to get various information about the file NewFile.txt.
We use the try-catch block to check if the file exists or not.
Deleting a File in Java:
A file can be deleted using java through the method delete(). We do not need to close the file as we do not use any reader or writer classes.
Code to Delete File using delete():
The output of the above code:
for Reading/inputting the data to the program
1)FileInputStream
//creating object for File class..
File f=new File("filelocation");
//create object for FileInputStream
FileInputStream fs=new FileInputStream(f);
2)BufferedInputStream
BufferedInputStream bis=new BufferedInputStream(fs);
3)FileReader
4)BufferedReader
5)File
Methods:
1)read():it reads the byte data from file
2)readLine():it reads the data by line
3)nextLine():cursor goes to nextline
---------------------------------------------------------
1.While working with files, we need to handle the Checked Exception in our code, otherwise our code will not compile.
2.FileReader class makes it possible to read the contents of a file as a stream of characters,
thus we are using in our code to read characters from a text file.
FileReader fr = new FileReader(filePath)
3.BufferedReader class provides buffering to our FileReader. Rather than reading one character at a time from the file,
we read a larger block at a time using BufferedReader.
FileReader fr = new FileReader(filePath);
BufferedReader txtReader = new BufferedReader(fr);
We can specify the buffer size in the above case we have used the default size(8192 chars).
Incase we want sized buffer our code will look like this:-
Int bufferSize = 1000;
BufferedReader txtReader = new BufferedReader(fr, bufferSize);
4.ReadLine, method of BufferedReader Class, which reads a line of text. A line is considered to be terminated by any one of a line feed
('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Code:-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WorkingwithFiles {
public static void main(String[] args) {
//FilePath
String sFilePath = "D:\\Automation\\Selenium\\TestFile.txt";
//Creating FileReader object
FileReader fr = null;
//Creating BufferedReader object
BufferedReader txtReader = null;
//Handling Exception using Try-Catch
try {
String sCurrentLine;
fr = new FileReader(sFilePath);
txtReader = new BufferedReader(fr);
//Reading file until file is null
while ((sCurrentLine = txtReader.readLine())!= null) {
System.out.println(sCurrentLine);
} //while loop ending
}catch(IOException e) {
e.printStackTrace();
} finally {
try {
if (txtReader != null)txtReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
========================================================================
writing/outputting the data from program to files
1)FileOutputStreamFileOutputStream fos=new FileOutputStream(filelocation);
2)BufferedOutputStream
BufferedOutputStream bos=new BufferedOutputStream(fos);
3)FileWriter
4)BufferedWriter
Method:
write(char c):write the data from program to file
write(byte b)
flush()--to flush out the stream.
newLine();
-------------------------------------------------------------------------------------------
Important Tips for Writing into a File:-
1.FileWriter class makes it possible to write a file as a stream of characters,
same like FileReader above.
FileWriter fw = new FileWriter(filepath);
2.Incase we want to control whether to append or overwrite into text file
Boolean append = true;
FileWriter fw = new FileWriter(filepath, append);
By Default it is “False”, thus it will overwrite the existing data.
3.BufferedWriter class provides buffering to our Write. Rather than write one character at a time
to the file, we write a larger block at a time. This is typically much faster, especially for disk access and larger data amounts
FileWriter fw = new FileWriter(path)
BufferedWriter bw = new BufferedWriter(fw)
We can control the size of bufferedwriter like we did in bufferedreader class
4.We used File objects to obtain information about a file or directory.File object is used to obtain information about a particular file or directory and is not used to read or write data, like length of a file
Code:-
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WritingInFiles {
public static void main(String[] args) {
//Data to write
String sContent = "Lets try to write newline into File";
//FilePath
String sFilePath = "D:\\Automation\\Selenium\\TestFile.txt";
try {
//Creating File object
File f = new File(sFilePath);
// if file doesn't exists, then create it
if(!f.exists()){
f.createNewFile();
}
//Creating FileWriter object
//using file object we got the filePath
FileWriter fw = new FileWriter(f.getAbsoluteFile());
//Creating BufferedWriter object
BufferedWriter bw = new BufferedWriter(fw);
//Writing content into file
bw.write(sContent);
//Adding new line
bw.newLine();
bw.close();
System.out.println("Data is Successfully written");
} catch (IOException e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.