Lesson Completion
Back to course

Module 15: File Handling and I/O

Overview

This module provides comprehensive coverage of file handling and input/output operations in Java, including traditional I/O, NIO (New I/O), file operations, serialization, and modern file system APIs.

Learning Objectives

  • Master file input/output operations
  • Understand streams and readers/writers
  • Work with NIO and NIO.2 APIs
  • Learn serialization and deserialization
  • Perform file system operations
  • Handle binary and text files
  • Implement efficient I/O operations

Topics Covered

15.1 Introduction to Java I/O

15.1.1 Understanding I/O

  • Input and Output Concept
  • Streams
  • Byte vs Character Streams
  • Buffering
  • I/O Exceptions

15.1.2 java.io Package

  • Core Classes Overview
  • Stream Classes
  • Reader/Writer Classes
  • File Classes
  • Serialization Support

15.1.3 I/O Streams Classification

  • Byte Streams
  • Character Streams
  • Input Streams
  • Output Streams
  • Processing Streams

15.2 Byte Streams

15.2.1 InputStream

  • Abstract Base Class
  • read() Methods
  • available()
  • skip()
  • close()

15.2.2 OutputStream

  • Abstract Base Class
  • write() Methods
  • flush()
  • close()

15.2.3 FileInputStream

  • Reading Binary Files
  • Constructor Options
  • Reading Bytes
  • Use Cases

15.2.4 FileOutputStream

  • Writing Binary Files
  • Constructor Options
  • Writing Bytes
  • Append Mode

15.2.5 BufferedInputStream

  • Buffered Reading
  • Performance Benefits
  • Buffer Size
  • mark() and reset()

15.2.6 BufferedOutputStream

  • Buffered Writing
  • Performance Benefits
  • Flushing Buffer
  • Buffer Size

15.2.7 DataInputStream

  • Reading Primitive Types
  • readInt(), readDouble(), etc.
  • Binary Format
  • Use Cases

15.2.8 DataOutputStream

  • Writing Primitive Types
  • writeInt(), writeDouble(), etc.
  • Binary Format
  • Use Cases

15.2.9 ByteArrayInputStream

  • In-Memory Stream
  • Byte Array Source
  • Testing
  • Use Cases

15.2.10 ByteArrayOutputStream

  • In-Memory Stream
  • Dynamic Byte Array
  • toByteArray()
  • Use Cases

15.3 Character Streams

15.3.1 Reader

  • Abstract Base Class
  • read() Methods
  • Character Handling
  • Encoding Support

15.3.2 Writer

  • Abstract Base Class
  • write() Methods
  • flush()
  • close()

15.3.3 FileReader

  • Reading Text Files
  • Default Encoding
  • Character Reading
  • Simple Text Files

15.3.4 FileWriter

  • Writing Text Files
  • Default Encoding
  • Character Writing
  • Append Mode

15.3.5 BufferedReader

  • Efficient Text Reading
  • readLine() Method
  • Large File Handling
  • Performance Benefits

15.3.6 BufferedWriter

  • Efficient Text Writing
  • newLine() Method
  • Buffering Benefits
  • Flushing

15.3.7 PrintWriter

  • Formatted Output
  • print(), println()
  • printf()
  • Auto-Flushing
  • Error Handling

15.3.8 InputStreamReader

  • Byte to Character Bridge
  • Encoding Specification
  • Charset
  • Conversion

15.3.9 OutputStreamWriter

  • Character to Byte Bridge
  • Encoding Specification
  • Charset
  • Conversion

15.3.10 CharArrayReader/Writer

  • In-Memory Character Streams
  • Char Arrays
  • Testing
  • Use Cases

15.3.11 StringReader/Writer

  • String-Based I/O
  • In-Memory Operations
  • Testing
  • Use Cases

15.4 File Class

15.4.1 Introduction to File Class

  • File and Directory Representation
  • Path Handling
  • Metadata Access
  • File Operations

15.4.2 Creating File Objects

  • Constructor Options
  • Absolute vs Relative Paths
  • Path Separators
  • Platform Independence

15.4.3 File Information Methods

  • exists()
  • isFile(), isDirectory()
  • length()
  • lastModified()
  • canRead(), canWrite(), canExecute()
  • isHidden()
  • getAbsolutePath()
  • getName(), getParent()

15.4.4 File Operations

  • createNewFile()
  • delete()
  • mkdir(), mkdirs()
  • renameTo()
  • setReadOnly()
  • setLastModified()

15.4.5 Directory Operations

  • list()
  • listFiles()
  • FileFilter
  • FilenameFilter
  • Directory Traversal

15.5 RandomAccessFile

15.5.1 Understanding RandomAccessFile

  • Non-Sequential Access
  • Reading and Writing
  • File Pointer
  • Mode Options (r, rw, etc.)

15.5.2 File Pointer Operations

  • seek()
  • getFilePointer()
  • length()
  • Random Access Patterns

15.5.3 Reading and Writing

  • read() and write()
  • readLine()
  • Primitive Type Methods
  • Use Cases

15.6 Serialization

15.6.1 Understanding Serialization

  • Object Persistence
  • Object State Saving
  • Network Transmission
  • Serializable Interface

15.6.2 ObjectOutputStream

  • Writing Objects
  • writeObject()
  • Serialization Process
  • File Output

15.6.3 ObjectInputStream

  • Reading Objects
  • readObject()
  • Deserialization Process
  • Type Casting

15.6.4 Serializable Interface

  • Marker Interface
  • serialVersionUID
  • Default Serialization
  • Inheritance

15.6.5 Transient Keyword

  • Excluding Fields
  • Sensitive Data
  • Non-Serializable Fields
  • Custom Handling

15.6.6 Custom Serialization

  • writeObject() Method
  • readObject() Method
  • Validation
  • Version Compatibility

15.6.7 Externalizable Interface

  • Complete Control
  • writeExternal()
  • readExternal()
  • Performance

15.6.8 Serialization Best Practices

  • serialVersionUID Declaration
  • Security Considerations
  • Version Compatibility
  • Alternative Formats (JSON, XML)

15.7 NIO (New I/O) - java.nio

15.7.1 Introduction to NIO

  • Non-Blocking I/O
  • Buffers and Channels
  • Selectors
  • Performance Benefits

15.7.2 Buffers

  • Buffer Concept
  • ByteBuffer
  • CharBuffer
  • Buffer Operations
    • put() and get()
    • flip(), clear(), rewind()
    • mark() and reset()
    • Capacity, Position, Limit

15.7.3 Channels

  • Channel Concept
  • FileChannel
  • SocketChannel
  • ServerSocketChannel
  • DatagramChannel
  • Reading and Writing

15.7.4 FileChannel

  • File Operations
  • transferTo(), transferFrom()
  • Memory-Mapped Files
  • File Locking
  • Performance

15.7.5 Charset and Encoding

  • Charset Class
  • Encoding/Decoding
  • Character Set Support
  • StandardCharsets

15.8 NIO.2 (Java 7+) - java.nio.file

15.8.1 Path Interface

  • Modern File Representation
  • Paths Class
  • Path Operations
  • Relative vs Absolute

15.8.2 Files Class

  • Utility Methods
  • Static Methods
  • File Operations
  • Directory Operations

15.8.3 Reading Files

  • Files.readAllBytes()
  • Files.readAllLines()
  • Files.lines() (Stream)
  • Files.newBufferedReader()
  • Efficient Reading

15.8.4 Writing Files

  • Files.write()
  • Files.writeString() (Java 11+)
  • Files.newBufferedWriter()
  • Append vs Overwrite

15.8.5 File Operations

  • Files.copy()
  • Files.move()
  • Files.delete()
  • Files.createFile()
  • Files.createDirectory()
  • Files.exists()

15.8.6 Directory Operations

  • Files.list()
  • Files.walk()
  • Files.walkFileTree()
  • Directory Streams
  • Recursive Traversal

15.8.7 File Attributes

  • BasicFileAttributes
  • PosixFileAttributes
  • DosFileAttributes
  • Files.getAttribute()
  • Files.setAttribute()
  • Metadata Access

15.8.8 File Watching

  • WatchService
  • File System Events
  • File Monitoring
  • Event Handling

15.8.9 Symbolic Links

  • Files.createSymbolicLink()
  • Files.isSymbolicLink()
  • Files.readSymbolicLink()
  • Link Handling

15.9 Scanner Class

15.9.1 Using Scanner for Input

  • Console Input
  • File Input
  • String Input
  • Token-Based Reading

15.9.2 Scanner Methods

  • next(), nextLine()
  • nextInt(), nextDouble()
  • hasNext(), hasNextInt()
  • Delimiters
  • Pattern Matching

15.9.3 Scanner Use Cases

  • User Input
  • File Parsing
  • Data Extraction
  • CSV Reading

15.10 Console Class

15.10.1 Console I/O

  • System.console()
  • readLine()
  • readPassword()
  • format()
  • Secure Input

15.11 File I/O Best Practices

15.11.1 Resource Management

  • Try-with-Resources
  • AutoCloseable
  • Proper Closing
  • Resource Leaks

15.11.2 Exception Handling

  • IOException
  • FileNotFoundException
  • Proper Error Handling
  • Error Recovery

15.11.3 Performance Optimization

  • Buffering
  • Batch Operations
  • Memory-Mapped Files
  • NIO vs Traditional I/O

15.11.4 Character Encoding

  • UTF-8 Default
  • Explicit Encoding
  • Platform Independence
  • Charset Handling

15.11.5 Path Handling

  • Platform-Independent Paths
  • File.separator
  • Path Normalization
  • Relative vs Absolute

15.12 Working with Different File Formats

15.12.1 Text Files

  • Line-Based Processing
  • CSV Files
  • Configuration Files
  • Log Files

15.12.2 Binary Files

  • Images
  • Audio/Video
  • Executables
  • Custom Binary Formats

15.12.3 Properties Files

  • Properties Class
  • load() and store()
  • Configuration Management
  • Application Settings

15.12.4 XML Files

  • DOM Parser
  • SAX Parser
  • StAX Parser
  • XPath

15.12.5 JSON Files

  • Third-Party Libraries
  • Jackson
  • Gson
  • JSON-B

15.13 Compression

15.13.1 ZIP Files

  • ZipInputStream
  • ZipOutputStream
  • ZipEntry
  • Creating/Extracting Archives

15.13.2 GZIP Files

  • GZIPInputStream
  • GZIPOutputStream
  • Compression/Decompression

15.14 Memory-Mapped Files

15.14.1 MappedByteBuffer

  • Virtual Memory Mapping
  • Large File Handling
  • Performance Benefits
  • Use Cases

15.15 File System Operations

15.15.1 File System Information

  • FileStore
  • Available Space
  • Total Space
  • File System Attributes

15.15.2 Temporary Files

  • Files.createTempFile()
  • Files.createTempDirectory()
  • Automatic Cleanup
  • Use Cases

Hands-on Exercises

  1. Read and write text files
  2. Copy files using different methods
  3. Implement file search program
  4. Create directory listing utility
  5. Build file compression tool
  6. Implement serialization examples
  7. Create file monitoring application
  8. Build CSV parser
  9. Implement file encryption/decryption
  10. Create log file analyzer
  11. Build file synchronization tool
  12. Implement backup utility

Key Takeaways

  • Java provides rich I/O APIs
  • Character streams for text, byte streams for binary
  • NIO.2 offers modern file operations
  • Always close resources properly
  • Buffering improves performance
  • Serialization saves object state
  • Path API is platform-independent

Common Mistakes to Avoid

  • Not closing resources
  • Ignoring character encoding
  • Platform-specific paths
  • Not handling IOException
  • Memory leaks with streams
  • Inefficient I/O without buffering
  • Unsafe deserialization

Real-World Applications

  • Log file processing
  • Data import/export
  • Configuration management
  • File upload/download
  • Backup systems
  • Data persistence
  • File system monitoring

Additional Resources

  • Java I/O Documentation
  • NIO Tutorial
  • Effective Java - I/O
  • File I/O Best Practices

Assessment

  • Quiz on I/O concepts
  • Practical: File manipulation programs
  • Serialization exercises
  • NIO.2 challenges
  • Performance optimization tasks

Previous Module

Module 14: Multithreading and Concurrency

Next Module

Module 16: Java 8 Features