File handling in Java is defined as reading and writing data to a file. The particular file class from the package called java.io allows us to handle and work with different formats of files. Thus, if we want to use a file class, we need to create an object of that particular class and should specify the filename or directory name.
If you want to deep dive further, do check out our Software Engineering Courses at Great Learning in collaboration with top engineering colleges and universities, including IIT Madras, Great Lakes, & IIIT Hyderabad. Participate in regularly organized career accelerated programs and placement drives offered by Great Learning and get hired by the top leading companies across different industries. Great Learning also offers a Java for beginners course if you wish to brush up your skills.
- Streams
- Understanding Streams
- Input and Output Streams
- The Classes for Input and Output
- Basic Input Stream Operations
- Basic Output Streams Operations
- The Standard Streams
- Reading and Writing Files
- Methods
- Object
- Java Directories
- Querying Files and Directories
Streams
As discussed above, the package that supports stream input/output is java.io, and it is vast. This package defines over seventy classes and interfaces, many of which have a large number of methods.
- It will be able to give you a chance to read files from the data.
- It will give us a chance to create a formatted line for the command.
- It will give us the chance to read or write basic data.
- It will give us a chance to read or write files containing objects.
Also Read: Java Tutorial for Beginners
Understanding Streams
The stream is the only representation of input or output that is maybe a source or destination of the data. We can also write the data in the stream or read the particular data from the stream. We can also visualize the stream of data as a sequence of bytes that flow out of the program.
Input and Output Streams
Writing data in the stream or to a stream is called an output stream. The particular output stream can go to any device which can connect through a hard disk or maybe any stream which can contain the sequence of bytes. An output stream also can be displayed on any output screen, which has its true capability. Stream output to your display is output to your command line. When you start writing something for your display screen, it can only display the characters but not the graphical content. Graphical output requires more specialized support.
You read data from an input stream. In principle, this can only be any source of serial data but is typically a disk file, the keyboard, or a remote computer.
Further, under normal circumstances, the file input and output you write in a machine can only be through a java application. It’s not available to java apples except strictly to a limited extent.
This has two advantages: First, you don’t have to worry about the detailed mechanics of each device, which are taken care of behind the scenes.
The streams which you write under the input and output can only have a small amount of data like a single character, but not more than that. Transferring data to or from a stream like this may be extremely inefficient, so a stream often equipped with a buffer in memory, in which case it is called a buffered stream.
The Classes for Input and Output
The logical structure forms with the number of stream classes. Once you know how they are related, you shouldn’t have much trouble using them. We will work through the class hierarchy from the top down, so you will be able to see how the classes hang together and how you can combine them in different ways to suit different situations.
java.io it contains all the classes for the support of the streams.
Class | Description |
Input Stream | The base class for byte stream input operations. |
Output Stream | The base class for byte stream output operations. |
Input Stream and Output Stream are both abstract classes.
Basic Input Stream Operations
As you saw in the previous statement, the Input Stream class is abstract, so you cannot create objects of this class type.
Method | Description |
read() | This method is abstract in the Input Stream class, so it has to be defined in a subway. This method returns the next byte available as stream int. Once the stream is getting towards an end, the method gives -1. An exception of type IOException will be thrown if an I/O error occurs. |
read(byte[] array) | It reads byte from the successive streams to the array. The maximum of array.length bytes will be read. This method will not return the data until the stream gets to the end. If the method will reach the end then it will not return the end of bytes. |
read(byte[] array, int offset, int length) | It works the same as the previous methods except the length. |
Basic Output Streams Operations
Independent output stream contains three write methods for writing the data into a stream. As can be expected, these mirrors the read() methods of the Input Stream class. This class is also abstract, so subclasses can be instantiated. The principal direct subclasses of Output Stream are shown.
- FileOutputStream – for writing to a file
- ObjectInputStream – for writing objects to a stream
- ByteArrayOutputStream – It is used to write the array of bytes
- PipeOutputStream – It is used for writing to a piped stream
- FilterOutputStream – it is used for filtering the output from an end stream
The Standard Streams
Your operating system will typically define three standard streams that are accessible through members of the system class in java:
- A Standard input stream that corresponds to the particular keyboard will be the default. This is encapsulated by the in a member of the system class and is of the type input stream.
- A Standard output stream will always correspond to the command line of the output. This is encapsulated by the out member of the system class and is of type print stream.
- A Standard error output stream for error messages that usually maps to the command-line output by default. It is also encapsulated by err members of a class system and print stream.
Reading and Writing Files
Reading files
The process we use for reading a file is quite similar to writing a file. First, you will obtain a file channel of an object from a file stream and also use the same channel to read the data for one or more buffers. Initially, you will be using a channel object that you obtain from a FileInputStream object to read a file. Later you will be using a FileChannel object obtained from a RandomAccessFile object to read and write the same file.
A FileInputStream object encapsulates a file that is essentially intended to be read, so the file must already exist and contain some data.
EXAMPLE:
FileInputStream inputFile = null;
// place to store the input stream reference
Try {
inputFile = new FileInputStream(*C:/Beg Java Stuff/myFile.txt*);
}
Catch(FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
Creating File Input Streams
A FileInputStream object encapsulates a file that it wants to read but it should already exist in the file and should also contain some data to read. It says that the constructor of a class in an object will be created in file only if it already exists.
There is a possibility even to use a file object that you have obtained by calling the getFD() method for an existing FileInputStream object, or possibly a random access file object.
File aFile = new File(* C:/Beg Java Stuff/myFile.text*);
FileInputStream inputFile1=null;
FileDescriptor fd=null;
Try {
// create the stream opened to write
inputFile1=new FileInputStream(aFile);
fd=inputFile1.getFD();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
// you can now create another input stream for the file from the file descriptor…
FileInputStream inputFile2=new FileInputStream(fd);
Once you have created the ObjectInputStream object, you call its readObject() method to read an object from the file.
Object myObject = null;
Try {
myObject = objectIn.readObject();
} catch(ClassNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1)
}
Writing Files
The process for writing a file is basically quite simple. For writing a file, you will load a file that you have created as one or more buffers and call a method for that particular object to write data to that file which is encapsulated by the file stream.
To start with, you will be using the simplest write() method for a file channel that writes the data contained in a single ByteBuffer object to a file. The number of bytes written to the file is determined by the buffers position and limit when the write() method executes.
To create a file in a specific directory, specify the path of the file and use double black slashes to escape the “” character.
C:\Users\MyName\filename.txt”); |
EXAMPLE:
File theFile = new File(“ MyFile”);
//Check out the file…
//Create the object output stream for the file
ObjectOutPutStream objectOut = null;
Try {
Objectout = new ObjectOutputStream(new FileOutputStream(theFile))
The five different exceptions that a channel write() operation will throw:
Exceptions |
NonWritableChannelException |
ClosedChannelException |
AsynchonousCloseException |
ClosedByInterruptException |
IOException |
Methods
canread() – It is a Boolean type and it says whether the file which we want is readable or not.
canwrite() – It is a Boolean type and it says whether the file which we want is writable or not.
createnewfile() – It is a Boolean type that says that the method creates an empty file.
delete() – It is a Boolean type which deletes a file which we want.
exist() – It is a Boolean type and says whether the file exists or not.
getname() – It is a string type which returns the file name or name of the file.
getabsolutepath() – It is a string type which returns the correct path of name of the file.
length() – It is a long type which returns the wanted size of the file in bytes.
list() – It is a string type which returns the array of the file in the directory.
mkdir() – It is a Boolean type which creates a directory.
File navigation and I/O
This concept comes as an input and output of a file where the flow of data that either you can read or you can write or you can perform read and write operations in a file permanently. Java uses these input and output streams to perform these tasks.
Object
- InputStream
- FileInputStream
- ByteArrayInputStream
- FileInputStream
- ObjectInputStream
- OutPutStream
- FileOutputStream
- ByteArrayOutputStream
- FileOutputStream
- ObjectOutputStream
An overview of file navigation and I/O is above diagram
Java Directories
Creating and Modifying Files and Directories directory
METHOD | DESCRIPTION |
renameTo(File path) | The file represented by the current object will be renamed to the path represented by the File object passed as an argument to the method. This does not change the current file object in your program and it alters the physical file. |
setreadonly() | Sets the file represented by the current object as read-only and returns true if the operation is successfully. |
mkdir() | Creates a directory with the path specified by the current file object. |
mkdirs() | Creates the directory represented by the current file object, including parent directories that are required. |
createnewfile() | Create a new empty file with the pathname defined by the current file object as long as the file does exist. |
delete() | This will delete the file and directory represented by the current file object and return true if the delete is successful. |
createDirectory(Path,FileAttribute</>) |
Querying Files and Directories
METHOD | DESCRIPTION |
exists() | Returns true if the file or directory referred to by the file object exists and false otherwise. |
isfile() | Returns true if the file object refers to an existing file and false otherwise. |
canread() | Returns true if you are permitted to read the file referred by the file object. |
canwrite() | Returns true if you are permitted to write the file referred by the file object. |
This brings us to the end of the blog on File Handling in Java.
Engaging in the study of Java programming suggests a keen interest in the realm of software development. For those embarking upon this journey with aspirations towards a career in this field, it is recommended to explore the following pages in order to acquire a comprehensive understanding of the development career path: