What Is File Handling in Java?

Introduction 

Due to its versatility, Java is still one of the most in-demand programming languages. We can work with files in Java, thanks to the File Class. The package java.io contains this File Class. Any programming language must include file handling since it enables us to store any program’s output in a file and carry out various operations. 

File handling is the process of reading from and writing to a file. In this article, we’ll examine all the related Java programming features and how to carry out file operations in Java. 

What Is File Handing in Java?  

Reading and writing data to a file are considered file handling in Java. The specific file class from the java.io package enables us to manage and operate with various file types. Thus, in order to use a file class, we must build an object of that specific type and provide the filename or directory name.  

Streams 

Java has a concept called stream that pipelines a series of objects to produce the desired outcome. A stream only accepts input from a group of I/O; hence it cannot be referred to as a data structure. 

  • Understanding Streams:  

A Java programmer can manage files using streams. In other words, streams can be used to read from or create files. A buffered reader and a file input stream reader can be used together to read a file. An application can then be shown a record from the file. In order to write a stream of data to a file, a file output writer and a print writer object can be used together. 

  • Input and Output Streams:  

An input stream of bytes is represented by the abstract superclass InputStream of the java.io package. InputStream is not useful by itself because it is an abstract class. Its subclasses, on the other hand, can read data. The Java.io package’s OutputStream class is the abstract superclass that describes an output bytes stream.OutputStream is not useful by itself because it is an abstract class. However, data can be written via its subclasses. 

Classes for Input and Output

The number of stream classes determine the logical structure. You shouldn’t have much trouble using them once you understand how they are connected. You will see how the classes fit together and how you can mix them to suit various situations as we work our way down the class hierarchy. 

  • Basic Input Stream Operations:  

Since the Input Stream class is abstract, you cannot make objects of this class type. It’s functions are as follows: 

  1. read(): This function needs to be defined in a module because it is abstract in the Input Stream class. The next byte accessible as stream int is returned by this procedure. The method returns -1 when the stream is close to ending. If there is an I/O error, an exception of type IO Exception will be thrown.
  2. read(byte[] array): The array is read bytes from the succeeding streams. The number of bytes read shall not exceed the array.length. Until the stream is finished, this method won’t return the data. 
  3. read(byte[] array, int offset, int length): Except for the length, it works just like the prior techniques.

// To create an InputStream: 

InputStream obj = new FileInputStreams(); 

  • Basic Output Stream Operations:  

Data is written using the output stream to a variety of output devices, including the monitor, file, etc. An output stream is modeled by the abstract superclass OutputStream. Because OutputStream is an abstract class, it is useless on its own. However, data is written via its subclasses. The OutputStream class has multiple subclasses, including the following: 

  • ByteArrayOutputStream 
  • FileOutputStream 
  • StringBufferOutputStream 
  • ObjectOutputStream 
  • DataOutputStream 
  • PrintStream 

// To create an Output Stream: 

OutputStream obj = new FileOutputStreams(); 

The Standard Streams 

All programming languages offer standard I/O, enabling a user’s program to accept keyboard input and produce output on the computer screen. If you are familiar with the C or C programming languages, three common devices—STDIN, STDOUT, and STDERR—must be understood. The following three regular streams are also made available by Java. 

  • Standard Input: This is used to send data into the user’s software. Typically, the standard input stream is a keyboard, and it is displayed as System.in. 
  • Standard Output: System.out is the name of the stream used to output the user’s program-generated data, which is typically shown on a computer screen. 
  • Standard Error: This is used to show error information from the user program, and is typically displayed as System.err for the standard error stream on a computer screen. 

Reading and Writing Files 

Let’s understand the methods of reading and writing files below. 

Reading Files: 

The method we use to read a file is quite similar to the method we use to write a file. In order to read the data for one or more buffers, you must first retrieve a file channel for an object from a file stream. To read a file at first, you will use a channel object that you get from a FileInputStream object. Later, you’ll read and write the same file using a FileChannel object that you got from a RandomAccessFile object. 

A file is essentially designed to be read by a FileInputStream object; therefore, it must already exist and have some data. 

public class ReadJava{ 

    public static void main(String[] args) 

    { 

        try { 

            File Obj = new File(“myfiles.txt”); 

            Scanner Reader = new Scanner(Obj); 

            while (Readers.hasNextLine()) { 

                String Alldata = Readers.nextLine(); 

                System.out.println(Alldata); 

            } 

            Reader.close(); 

        } 

        catch (FileNotFoundException x) { 

            System.out.println(“An error occurred.”); 

            e.printStackTrace(); 

        } 

    } 

} 

Writing Files: 

Fundamentally, writing a file is a straightforward operation. In order to write data to a file, you must load the file you created as one or more buffers and then execute the function for that specific object to write the data to the file, which is included within the file stream. 

The simplest write() function for a file channel that publishes the data contained in a single ByteBuffer object to a file will be used initially. When the write method is used, the buffers’ position and limit control how many bytes are written to the file. 

public class WriteJava{ 

    public static void main(String[] args) 

    { 

        try { 

            FileWrite Write 

                = new FileWrite(“myfile.txt”); 

            Write.write( 

                “Files in Java are really good!!”); 

            Write.close(); 

            System.out.println(“written successfully .”); 

        } 

        catch (IOException e) { 

            System.out.println(“error occurred.”); 

            e.printStackTrace(); 

        } 

    } 

} 

Methods of Java File Operations 

Java offers a variety of file-handling methods that can be used to carry out different tasks, like creating a file using createNewFile(). The following is a list of several popular file-handling techniques: 

  • createNewFile(): It is a Boolean-type function that creates a blank file. 
  • mkdir(): A Boolean method for creating a directory. 
  • delete(): It is a method of the Boolean type that deletes a file. 
  • getName(): It is a method that returns the file name as a string. 
  • getAbsolutePath(): A string-type function for obtaining the file path. 
  • list(): It is a function that takes a string argument and returns an array of files from a directory. 
  • Read(): A boolean-type method that determines whether or not the file can be read. 
  • Write(): It is a boolean-type method that determines whether or not a file can be modified. 
  • exists(): It is a Boolean-type method that determines whether the given file is present. 
  • length(): It is a long type function that returns a file’s size in bytes.
  • Write(): The write() function is used to write data to files.
  • Line(): This function is used to read the contents of a given file. 

Java Directories 

The following is a list of Java directories: 

  • renameTo(File path): It changes the name of the file represented by the current object to the path indicated by the File object that is supplied as an argument to the method. This modifies the physical file but does not affect the current file object in your program. 
  • setreadonly(): It marks the current object’s file as read-only and returns true if the action is successful. 
  • mkdir(): The mkdir() function creates a directory with the path defined by the active file object. 
  • mkdirs(): It creates the directory that the current file object represents, along with any necessary parent directories. 
  • createnewfile(): If the file exists, creates a new empty file with the pathname provided by the current file object. 
  • delete(): The current file object’s file and directory will be deleted, and if the delete was successful, true will be returned. 

Querying Files and Directories in Java 

Functions fpr querying files and directories via Java file handling are the following: 

  • exists(): It determines if the abstract filename refers to a file or directory already existing and brings back genuine Otherwise false if the abstract file path exists. 
  • isfile(): When a filename is represented by an abstract filename, the isfile() function determines if it is a file or a directory. If the abstract file path is File, it returns true; otherwise, it returns false. 
  • Canread(): It determines whether it is possible to read the file specified by the abstract pathname. If the program is authorized to read the file and the file path exists, it returns true; otherwise, it returns false. 
  • Canwrite(): It examines a program’s ability to write to the file indicated by an abstract pathname. If the abstract file path exists and the program is allowed to write to it, the return value is true; otherwise, it is false. 
  • canExecute(): It determines whether or not the file specified by the abstract pathname can be executed. If the file path exists and the application is allowed to execute it, the return value is true; otherwise, it is false. 

Conclusion 

File handling in Java is simply the process of reading data from a file and writing that data into a file. Java has a built-in class called “File” that lets us carry out any kind of operation on a file. The import keyword is used to import the File class before using any of its methods to achieve the functionality of the File class, which includes creating and deleting files, retrieving file information, and other operations.  

This article thoroughly introduces Java file handling, explaining what it is, how to do it, and how to work with files. Check out the UNext platform for learning Java programming at a professional level and explore cutting-edge courses for upskilling purposes. 

Related Articles

loader
Please wait while your application is being created.
Request Callback