Java

File Handling

Read and write files in Java. Use the File class, FileReader, and FileWriter.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Read and write files in Java. Use the File class, FileReader, and FileWriter. This hands-on tutorial focuses on practical implementation of file handling concepts.

File Handling

Java provides the java.io package for file handling.

The File Class

This class is an abstract representation of file and directory pathnames.

import java.io.File;

File myFile = new File("filename.txt");

Useful Methods

  • canRead()
  • canWrite()
  • createNewFile()
  • delete()
  • exists()
  • length()

Writing to a File

Use FileWriter.

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

try {
  FileWriter myWriter = new FileWriter("filename.txt");
  myWriter.write("Java is fun!");
  myWriter.close();
} catch (IOException e) {
  e.printStackTrace();
}

Reading from a File

Use Scanner (easiest) or FileReader.

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

File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
  String data = myReader.nextLine();
  System.out.println(data);
}
myReader.close();

Interactive Code

Note: In a browser environment, file access is restricted. This code demonstrates the syntax.

JAVA PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "Java File class operations: creation, reading and writing"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 3

Which class is used to read data from a text file nicely?

File
Scanner
Printer

Next Steps

For advanced I/O (like sending Objects over a network), we need Streams & Serialization.