File Handling in Java with CRUD Operations


Record taking care of is a fundamental angle of programming, permitting us to associate it with records put away on our computer. In Java, record dealing is made helpful through the Record course and different operations, collectively known as CRUD (Make, Read, Upgrade, Delete) operations. In this article, we are going to investigate distinctive approaches to perform record dealing in Java, each advertising its claim preferences and utilizing cases.

Syntax

Some time recently jumping into the different approaches of file operations, let's familiarize ourselves with the basic language structure for making record in Java −

File file = new File("path/to/file.txt");

Explanation of Syntax

To start record dealing with Java, we ought to moment the fundamental classes utilizing the moment articulation. The Record class allows us to make an occasion speaking to a record by giving the file's way as a parameter. Once we have the record question, we are able to perform different operations like reading, writing, updating, and deleting the file.

Approach 1: Using FileReader and FileWriter

Algorithm

  • Create a FileReader object to read from an existing file.

  • Create a FileWriter object to write to a file.

  • Use a loop to read from the input file and write to the output file until the end of the file is reached.

  • Close the FileReader and FileWriter objects to release system resources.

Example

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileHandler {
   public static void main(String[] args) {
      try {
         FileReader reader = new FileReader("input.txt");
         FileWriter writer = new FileWriter("output.txt");

         int character;
         while ((character = reader.read()) != -1) {
            writer.write(character);
         }

         reader.close();
         writer.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Hello, world! This is a sample text file used for testing the file handling code. It contains some random sentences and paragraphs. Feel free to modify and experiment with it as needed. Have a great day!

Explanation

In this approach, we utilize the FileReader class to read from an existing record and the FileWriter class to type into a record. We make FileReader and FileWriter objects, indicate the input and yield record names, and after that utilize a while loop to examine characters from the input record and type in them to the yield record. At last, we near the FileReader and FileWriter objects to release system resources.

Approach 2: Using BufferedReader and BufferedWriter

Algorithm

  • Create a BufferedReader object to read from an existing file.

  • Create a BufferedWriter object to write to a file.

  • Use a loop to read from the input file and write to the output file until the end of the file is reached.

  • Close the BufferedReader and BufferedWriter objects to release system resources.

Example

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileHandler {
   public static void main(String[] args) {
      try {
         BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
         BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));

         String line;
         while ((line = reader.readLine()) != null) {
            writer.write(line);
            writer.newLine();
         }

         reader.close();
         writer.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Hello, world! This is a sample text file used for testing the file handling code. It contains some random sentences and paragraphs. Feel free to modify and experiment with it as needed. Have a great day!

Explanation

In this approach, we utilize the BufferedReader class to read from an existing record and the BufferedWriter lesson to type into a record. We make BufferedReader and BufferedWriter objects, indicate the input and yield record names, and after that utilize a circle to study lines from the input record and compose them to the yield record. By using the readLine() strategy, it is ready to handle content input more effectively. At long last, we near the BufferedReader and BufferedWriter objects to release system assets.

Approach 3: Using FileInputStream and FileOutputStream

Algorithm

  • Create a FileInputStream object to read from an existing file.

  • Create a FileOutputStream object to write to a file.

  • Use a loop to read from the input file and write to the output file until the end of the file is reached.

  • Close the FileInputStream and FileOutputStream objects to release system resources.

Example

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileHandler {
   public static void main(String[] args) {
      try {
         FileInputStream inputStream = new FileInputStream("input.txt");
         FileOutputStream outputStream = new FileOutputStream("output.txt");

         int bytesRead;
         byte[] buffer = new byte[1024];
         while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
         }

         inputStream.close();
         outputStream.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Hello, world! This is a sample text file used for testing the file handling code. It contains some random sentences and paragraphs. Feel free to modify and experiment with it as needed. Have a great day!

Explanation

Here, we make use of FileInputStream to study from an existing record and FileOutputStream to type into a record. We make FileInputStream and FileOutputStream objects, indicate the input and yield record names, and after that utilize a circle to peruse bytes from the input record and type in them to the yield record. The buffer makes a difference in proficient perusing and composing of information. Finally, we close the FileInputStream and FileOutputStream objects to release system resources.

Approach 4: Using Files.copy() and Files.delete()

Algorithm

  • Use the Files.copy() method to copy the contents from one file to another.

  • Use the Files.delete() method to delete a file.

Example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileHandler {
   public static void main(String[] args) {
      try {
         Path source = Paths.get("input.txt");
         Path destination = Paths.get("output.txt");
         Files.copy(source, destination);

         Files.delete(source);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

Hello, world! This is a sample text file used for testing the file handling code. It contains some random sentences and paragraphs. Feel free to modify and experiment with it as needed. Have a great day!

Explanation

In this approach, we utilize the Records course from the java.nio.file bundle to duplicate and erase records. We indicate the source and goal record ways utilizing the Ways lesson and after that utilize the copy() strategy to duplicate the substance of the source record to the goal record. After the duplicate operation is total, we utilize the delete() strategy to erase the source record. This approach gives a brief and effective way to perform record replicating and cancellation.

Conclusion

Record taking care of is an on a very basic level portion of Java programming, and understanding different approaches to perform CRUD operations can essentially overhaul your capacity to work with records. In this article, we explored four approaches to record taking care of in Java, each with its claim inclinations and utilize cases. By utilizing classes such as FileReader, FileWriter, BufferedReader, BufferedWriter, FileInputStream, FileOutputStream, and Records, we are able to easily make, read, update, and erase records in our Java programs. Testing with these approaches will assist you create a strong record dealing with functionalities to suit your particular application necessities.

Updated on: 31-Jul-2023

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements