File Handling in Java

Mannan Ul Haq
0
The `java.io.File` class in Java is the gateway to interact with files in your system. The `java.io` package provides various classes to perform a multitude of operations on files, such as creating new files, reading from existing ones, writing to files, and more.

import java.io.File; // Include the java.io.File class

File file = new File("filePath"); // Instantiate a File object

Below are some commonly used methods provided by the `File` class:
  • `createNewFile()`: Use this method to create a new file. If the file already exists, it does not overwrite it but returns `false`.
  • `delete()`: This method removes a file or directory.
  • `exists()`: This method checks if a file or directory exists at the specified path.
  • `getName()`: This method returns the name of the file or directory.
  • `getAbsolutePath()`: This method returns the absolute path of the file or directory.
  • `length()`: This method returns the size of the file in bytes.
  • `list()`: This method returns an array of strings denoting the files and directories in the directory represented by this `File` object.

To handle exceptions which might occur during these operations, it's often necessary to import `FileNotFoundException` and `IOException`.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

However, merely creating or deleting files doesn't serve all purposes. Often, we need to write to and read from files. For writing to files, we have `PrintWriter`.

The `PrintWriter` class in Java provides capabilities to write formatted data to a text-output stream. It's a character-based class, as opposed to byte-based streams, which means it's generally used to write text.

Here are some commonly used methods of the `PrintWriter` class:
  • PrintWriter(File file): This method constructs a new `PrintWriter`, without automatic line flushing, with the specified file.
  • print(String s): This method prints a string. If the argument is `null`, it prints "null".
  • println(): This method terminates the current line by writing the line separator string.
  • println(String x): This method prints a String and then terminates the line. If the argument is `null`, it prints "null".
  • printf(String format, Object... args): This method writes a formatted string to this writer using the specified format string and arguments.
  • close(): This method closes the `PrintWriter`, flushing it first.
  • checkError(): This method flushes the stream and checks its error state.

Here's a basic example that illustrates writing to and reading from a file. We'll use the `PrintWriter` class to write content to the file and `Scanner` class to read the content.

import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.Scanner;

class Main
{
    public static void main(String[] args)
    {
        try
        {
            // Define a string message
            String message = "Java makes file handling easy!";

            // Create a File object for myfile.txt
            File file = new File("myfile.txt");

            // Create a PrintWriter and write the message to myfile.txt
            PrintWriter writer = new PrintWriter(file);
            writer.println(message);
            writer.close(); // Always close the writer

            // Create a Scanner and read the contents of myfile.txt
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine())
            {
                String line = scanner.nextLine();
                System.out.println(line);  // Display the content of myfile.txt
            }
            scanner.close(); // Always close the scanner
        }
        catch (FileNotFoundException e)
        {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

In the provided code, we first define a string `message`. Then we create a `File` object for "myfile.txt". Using a `PrintWriter` instance, we write the `message` into the file. If "myfile.txt" doesn't exist, it will be created. If it does exist, the previous content will be overwritten.

Next, we create a `Scanner` instance to read the content of "myfile.txt". We keep reading each line using `scanner.nextLine()` until there is no line left in the file. The content of the file is then printed out to the console.

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !