Nearby lessons

54 of 125

Java - The File Class

📌 What You Will Learn
  • What a stream is and how data flows
  • Byte streams vs character streams
  • Reading and writing text files easily
  • The modern File methods and Scanner input
  • Serialization — saving an object to a file

The File Class is a core concept of the Java language. This lesson explains The File Class — File Information and The File Class — Full Toolkit with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The File Class — File Information

The File class does not read or write data — it gives information about files and folders, and helps create/delete them.

Example01
JCode Cell
1import java.io.File;
2 
3class FileInfo {
4 public static void main(String[] args) {
5 File f = new File("notes.txt");
6 System.out.println("Exists? " + f.exists());
7 System.out.println("Name: " + f.getName());
8 System.out.println("Size: " + f.length() + " bytes");
9 System.out.println("Readable? " + f.canRead());
10 System.out.println("Path: " + f.getAbsolutePath());
11 }
12}
Output
Exists? true Name: notes.txt Size: 53 bytes Readable? true Path: C:\Users\admin\Desktop\JS\notes.txt

The File Class — Full Toolkit

The File class (in java.io) represents a file or a folder. Creating a File object does not create the file — you must call a method:

MethodWhat it does
createNewFile()Actually creates the file on disk (returns true/false)
mkdir()Creates a directory
exists()Does the file/folder exist?
isFile() / isDirectory()Is it a file / a folder?
length()Size in bytes
getName()Just the name
getAbsolutePath()Full path
delete()Deletes the file
renameTo(newFile)Renames the file
listFiles()All files/folders inside a directory (returns File[])
lastModified()Last modification time
Example02
JCode Cell
1import java.io.File;
2 
3class FileTools {
4 public static void main(String[] args) throws Exception {
5 File dir = new File("c:/myfolder");
6 if (!dir.exists()) {
7 dir.mkdir(); // create the folder
8 }
9 File f = new File(dir, "notes.txt");
10 f.createNewFile(); // create the file
11 
12 System.out.println("Is file? " + f.isFile());
13 System.out.println("Size: " + f.length() + " bytes");
14 System.out.println("Path: " + f.getAbsolutePath());
15 }
16}
📝 Key Takeaways
  • A stream is a flow of data: input brings data in, output sends it out.
  • Byte streams (InputStream/OutputStream) for images/videos; character streams (Reader/Writer) for text.
  • Wrap FileReader in BufferedReader to read text line by line.
  • Scanner is the simplest way to read input from the keyboard.
  • The File class gives file information; it does not read data.
  • Serialization saves objects to files; transient fields are not saved.
  • Always close streams — or better, use try-with-resources.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1