File Handling in Java

All the classes that you may require on a day to day I/O programming basis are contained in the package java.io. The streams present in this package broadly represent output and input locations. Moreover, the streams supported in Java include object, primitives and localized characters. A stream can simply be described as data, arranged in a sequence. While the inputStream can be used for inputting data from a source, the OutputStream can be sued for outputting data to a sink. The support for I/O provided by Java is flexible and extensive. This post sims to cover all the basic facets of File Handling in Java.

Byte Streams

Byte streams in Java are utilized to perform output and input of 8-bit bytes. In spite of the fact that there are numerous classes identified with byte streams yet most utilized classes are, Fileoutputstream and Fileinputstream. Here is an example of they can be used in real-life programming.

import java.io.*;
public class Filecopy {
public static void main(string args[]) throws IOException {
FileInputStream inputx = invalid;
FileOutputStream outputx = invalid;
try {
inputx = new FileInputStream(“inputfile.txt”);
outputx = new FileOutputStream(“outputfile.txt”);
int charx;
while ((charx = inputx.read()) != -1) {
outputx.write(charx);
}
}
finally {
if (inputx != invalid) {inputx.close();
}
if (outputx != invalid) {
outputx.close();
}
}
}

Presently we should have a record inputfile.txt with the accompanying content:

This is for testing purpose only.

As an important step, compile and execute the code shown above. The execution of the code shall result in the creation of outputfile.txt file.

Character Streams

Java Byte streams are utilized to perform output and input of 8-bit bytes. On the other hand, Java Character streams are utilized to perform output and input for 16-bit unicode. In spite of the fact that there are numerous classes identified with character streams yet the most commonly used ones include Filereader and Filewriter.

It is worth mentioning here that the implementation of Filereader utilizes Fileinputstream and Filewriter utilizes Fileoutputstream. This may make you wonder as to what is the difference between the former and latter. Filereader peruses two bytes at once and Filewriter composes two bytes at once. We can re-compose above sample which makes utilization of these two classes to duplicate an info record (having unicode characters) into an outputfile.txt.

import java.io.*;
public class Mycopyfile {
public static void main(string args[]) throws IOException {
FileReader inputx = invalid;
FileWriter outputx = invalid;
try {
inputx = new FileReader(“inputfile.txt”);outputx = new FileWriter(“outputfile.txt”);
int charx;
while ((charx = inputx.read()) != -1) {
outputx.write(charx);
}
}
finally {
if (inputx != invalid) {
inputx.close();
}
if (outputx != invalid) {
outputx.close();
}
}
}

Presently how about we have a record inputfile.txt with the accompanying text:

This is for testing purpose only.

Compile and execute the file containing this code. The execution of this code should create an output file outputfile.txt.

Standard Streams

All the programming languages give backing to standard I/O where client’s code can take information from a console and afterward deliver appropriate output on the machine screen. On the off chance that you have some knowledge of C or C++, then you must be mindful of three standard tools namely, STDIN, STDOUT and STDERR. Java provides three standard streams, which are discussed below:

  • Standard Error: This is utilized to yield the error information created by the client’s code and normally a machine screen is utilized as standard error stream and referred to as System.err.
  • Standard Output: This is utilized to yield the information created by the client’scode and normally a machine screen is utilized to standard output stream and referred to as System.out.
  • Standard Input: This is utilized to encourage the information to client’s code and normally a console is utilized as standard data stream and referred to as System.in.

Sample Implementation:
import java.io.*;
public class Myreadconsole {
public static void main(string args[]) throws IOException {
InputStreamReader cinx = invalid;
try {
cinx = new InputStreamReader(system.in);
System.out.println(“Input string, press “e” to exit.”);
char charx;
do {
charx = (char) cinx.read();
System.out.print(charx);
} while(charx != ‘e’);
}
finally {
if (cinx != invalid) {
cinx.close();
}
}
}

The code mentioned above must be saved in a file named Myreadconsole.java. Upon compilation and execution of this code, the system must be able to receive and interpret characters.

Perusing and Writing Files

As mentioned, a stream can be defined as a sequence of information. The Inputstream is utilized to peruse information from a source and the Outputstream is utilized for outputting information to a terminus.

Here is a chain of importance of classes to manage Input and Output streams. The two essential streams are Fileinputstream and Fileoutputstream, which would be talked about in the following section:

Fileinputstream:

This stream is utilized for perusing information from the documents. Objects can be made utilizing the keyword new and there are a few sorts of constructors accessible. Inputstream can be used for reading files in the following manner:

Inputstream myfx = new Fileinputstream(“c:/java/hi”);

The constructor takes a record item to make a data stream object to peruse the document. Initially, we make a record item utilizing File() technique in the following manner:

File myfx = new File(“c:/java/hi”);

Inputstream myfx = new Fileinputstream(myfx);

When you have the object of Inputstream under control, there is a rundown of assistant methods, which can be utilized to peruse to stream or to do different operations on the stream.

  • protected void finalize() throws IOException {}
    This system cleans up any association with the file and guarantees that the local method for this output stream for the file is called. Besides this, this method is also capable of throwing an exception.
  • public void close() throws IOException {}
    This system shuts the output stream of the file and discharges any framework assets connected with the the same. It is also capable of throwing an exception.
  • public int available() throws IOException{}
    This function returns an int, indicating the number of bytes that the input stream can still read.
  • public int read(int r)throws IOException{}
    The read method is used for reading content from the InputStream and returns thenext byte of data in int data type. However, upon reaching the end of file, it returns -1.
  • public int read(byte[] r) throws IOException{}
    This read method is similar in operation to the read method described above with the exception that it reads data length of r in the given array. The function returns the number of bytes read and -1 upon reaching the end of file.

Other input streams are also available for use. Some of these include:

  • DataInputStream
  • ByteArrayInputStream

FileOutputStream:

Fileoutputstream is utilized to make a file and write text into it. The stream would create a file, in the event that it doesn’t as of now exist, before opening it for outputting. Here are two constructors which can be utilized to make a Fileoutputstream object.

Method 1:
OutputStream myfx = new FileOutputStream(“c:/java/hi”)

Method 2:
File myfx = new File(“c:/java/hi”);
OutputStream myfx = new FileOutputStream(myfx);

When you have OutputStream object under control, there is a rundown of aide methods, which can be utilized to keep in touch with stream or to do different operations on the stream.

  • public void write(int w) throws IOException {}
    This method composes the tagged byte to the output stream.
  • protected void finalize() throws IOException {}
    This strategy cleans up any associations with the record. Besides this, it also guarantees that the local method for this output stream for file is called. This method is capable of throwing an exception.
  • public void close() throws IOException {}
    This method shuts the output stream of the file. Moreover, it discharges anyframework assets connected with the document. This method also throws an IOException.
  • public void write(byte[] w)
    This method composes w.length bytes from the specified byte exhibit to the Outputstream.

There are other imperative output streams accessible, which are as follows:

  • ByteArrayOutputStream
  • DataOutputStream

Sample Implementations:
import java.io.*;
public class Mytestfile{
public static void main(string args[]){
try{
byte bytewrite [] = {45,64,22,49,1};
OutputStream myos = new FileOutputStream(“mytest.txt”);
for(int i=0; i < bytewrite.length ; i++){
myos.write( bytewrite[x] );
}
myos.close();
InputStream myis = new FileInputStream(“mytest.txt”);
int sizex = myis.available();
for(int z=0; z< sizex; z++){
System.out.print((char)myis.read() + “ “);
}
myis.close();
}catch(IOException e){
System.out.print(“Exception Caught!”);}
}

The above code would make a file mytest.txt and would compose given numbers in parallel organization. Same would be outputted to the stdout screen.

File Navigation and I/O

There are a few different classes that we would be experiencing to get to know the fundamentals of File Navigation and I/O.

  • File Class
  • FileWriter Class
  • FileReader Class

Directories

A directory is a File, which can contains a rundown of different catalogs and files. You utilize the object File to make catalogs, to rundown down documents accessible in an index. For complete point of interest check a rundown of every last one of techniques which you can approach File item and what are identified with indexes.

Making Directories:

There are two valuable File utility methods, which can be utilized to make directories:

  • The mkdirs() method makes both a directory and all the elements of the index.
  • The mkdir( ) method makes a directory, returning valid on achievement and false on disappointment. Failure demonstrates that the way determined in the File object exists, or that the index can’t be made in light of the fact that the whole way does not exist yet.

Sample Implementation:
import java.io.File;
public class MyCreateDir {
public static void main(String args[]) {
String directoryname = “/tmp/user/java/bin”;
File dir = new File(directoryname);
dir.mkdirs();}
}

Listing Directories:

You can utilize list( ) method provided by the File class to provide a list of all the records and directories accessible in an index.

Sample Implementation:
import java.io.File;
public class MyReadDir {
public static void main(String[] args) {
File myfile = null;
String[] paths;
try{
myfile = new File(“/tmp”);
mypaths = file.list();
for(String path:mypaths)
{
System.out.println(path);
}
}catch(Exception e){
e.printStackTrace();
}
}
}