DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-78 Java File Handling

File handling in Java allows us to create, read, update, and delete files through built-in classes. Java provides powerful APIs to work with files and directories in the java.io package.

1. The File Class in Java

The File class (in java.io package) is used to represent file and directory pathnames. It does not directly deal with the content of files; instead, it provides methods to create, delete, and get file information.

2. Common Methods in the File Class

  • createNewFile() – Creates a new file
  • delete() – Deletes the file
  • canExecute() – Checks if file is executable
  • canRead() – Checks if file is readable
  • canWrite() – Checks if file is writable
  • exists() – Checks if file exists
  • getAbsolutePath() – Returns absolute path
  • getName() – Returns file name
  • isDirectory() – Checks if path is directory
  • isFile() – Checks if path is file
  • isHidden() – Checks if file is hidden
  • lastModified() – Returns last modified time
  • renameTo(File Name) – Renames file
  • setExecutable(boolean) – Sets executable permission
  • setReadable(boolean) – Sets readable permission
  • setWritable(boolean) – Sets writable permission
  • listFiles() – Lists files in a directory

3. File Reading and Writing

FileWriter and BufferedWriter

  • FileWriter is used to write characters to a file.
  • BufferedWriter provides efficient writing by buffering data.

FileReader and BufferedReader

  • FileReader reads characters from a file.
  • BufferedReader reads text efficiently and allows reading line by line.

4. Key Points

  • Always close streams or use try-with-resources for automatic closing.
  • BufferedReader and BufferedWriter improve performance.
  • File class is for metadata and file management, not content reading/writing.

5. Example Program

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileDemo {
    public static void main(String[] args) {
        File myFile = new File("D:\\Tamil\\Hi.txt");
        try {
            myFile.createNewFile();
            System.out.println("File created successfully.");

            FileWriter writer = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(writer);

            bw.write("Tamilselvan K");
            bw.newLine();
            bw.write("hii");
            bw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)