Nearby lessons
56 of 125Java - Working with Directories
📌 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
Working with Directories is a core concept of the Java language. This lesson explains 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 — 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:
| Method | What 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 |
Example01
📝 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 QuestionsProgress: 0 / 1