
File handling in Java is one of the most important functions of java. We read from a file and write to a file.
When writing to a file, the source from where it is read can be anything. It can be database, a string or another file.
How to create a file?
File class which is part of the java.io package is used for the creation of a file
File obj = new File("testFile.txt");
How to read a file?
try {
//First we create an Object to read from the input file.
File fileObj = new File("C\\:FileTest.txt");
Scanner fileReader = new Scanner(fileObj);
while (fileReader.hasNextLine()) {
String data = fileReader.nextLine();
System.out.println(data);
}
fileReader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
Above we have used a scanner to read from a file. But there are other utilities available as well.
There are 2 ways in which data is read from a file.
1)Stream of Bytes: Here data is read from a file as a stream of bytes. You an say read as binary format. FileInputStream is the class which does that.
2)Stream of Characters: Here data is read from a file as sequence of text/characters. You can say read as unicode format. FileReader is the class to read text data.
Difference between an InputStream and a Reader in Java? Both InputStream and Reader are ways to read data from the source , which can be either file or socket, but main difference between them is that InputStream is used to read binary data while Reader is used to read text data, precisely Unicode characters.
Let’s see the below implementation for FileInputStream and FileReader.
//Reading File using InputStream
try (FileInputStream fis = new FileInputStream("testFile.txt"))
{
int data = fis.read();
while (data != -1)
{
System.out.print(Integer.toHexString(data));
data = fis.read();
}
}
catch (IOException e)
{
System.out.println("Failed to read binary data from File");
e.printStackTrace();
}
// Reading File data using FileReader in Java
try
(
FileReader reader = new FileReader("testFile.txt"))
{
int char = reader.read();
while (character != -1)
{
System.out.print((char) character);
character = reader.read();
}
}
catch (IOException io)
{
System.out.println("Character data reading from File failed");
io.printStackTrace();
}
read():
The read()
method of the FileInputStream
/FileReader class returns an int
which contains the byte value or char value of the byte/char read. If the read()
method returns -1, there is no more data to read in the FileInputStream
/FileReader, and it can be closed. That is, -1 as int value, not -1 as byte value
BufferedReader & BufferedOutputStream
Another way to read from a file is using the BufferedReader/BufferedInputStream Class. If no of reads are more, then BufferedReader/BufferedInputStream is preferable as it buffers the read characters/bytes in internal memory rather than reading and writing directly. The buffer size may be specified, or the default size may be used.
Writing to a file:
To write into a file also there are many tools available.
Let’s see a basic example using FileWriter class.
try {
FileWriter testWriter = new FileWriter("TestFile.txt");
testWriter.write("Writing into test file to test file writer");
// Closing the resources allocated
testWriter.close();
System.out.println("Successfully written in the file.");
} catch (IOException e) {
System.out.println("An exception occurred.");
e.printStackTrace();
}
Apart from FileWriter Class, Similarly for file writing we have BufferedWriter and FileOutputStream class as well.
FileWriter writes directly into Files and should be used only when the number of writes is less. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better. FileOutputStream writes stream of bytes.