Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 10 of 10 · File Handling and I/O Operations
Interview question

What are common patterns and best practices for file handling in Java? Java में file handling के लिए common patterns और best practices कौन सी हैं?

Answer

Best practices for file I/O include using try-with-resources, buffering, proper exception handling, checking file existence, and choosing appropriate streams based on data type.

import java.io.*;
import java.nio.file.*;
import java.util.*;

public class FileHandlingBestPractices {
    
    // Pattern 1: Reading file line by line
    public static void readFileLinesPattern(String filePath) {
        try (BufferedReader reader = new BufferedReader(
                new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println('Error reading file: ' + e.getMessage());
        }
    }
    
    // Pattern 2: Writing content to file
    public static void writeFilePattern(String filePath, String content) {
        try (BufferedWriter writer = new BufferedWriter(
                new FileWriter(filePath))) {
            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            System.err.println('Error writing file: ' + e.getMessage());
        }
    }
    
    // Pattern 3: Safe file operations
    public static void safeFileOperations(String filePath) {
        File file = new File(filePath);
        
        // Check before operations
        if (!file.exists()) {
            System.out.println('File does not exist');
            return;
        }
        
        if (!file.canRead()) {
            System.out.println('File not readable');
            return;
        }
        
        if (file.length() > 10_000_000) {
            System.out.println('File too large');
            return;
        }
        
        // Process file
    }
    
    // Pattern 4: Efficient batch processing
    public static void processLargeFileEfficiently(String filePath) {
        try (BufferedReader reader = new BufferedReader(
                new FileReader(filePath), 65536)) {  // 64KB buffer
            String line;
            while ((line = reader.readLine()) != null) {
                // Process line
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // Pattern 5: Using Java 7+ Files API
    public static void modernFileHandling(String filePath) {
        try {
            // Read entire file
            List<String> lines = Files.readAllLines(Paths.get(filePath));
            
            // Process
            lines.stream()
                    .filter(line -> !line.isEmpty())
                    .forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // Pattern 6: Error handling and logging
    public static void robustFileHandling(String filePath) {
        try (BufferedReader reader = new BufferedReader(
                new FileReader(filePath))) {
            String line;
            int lineNo = 0;
            while ((line = reader.readLine()) != null) {
                lineNo++;
                try {
                    // Process line
                } catch (Exception e) {
                    System.err.println('Error at line ' + lineNo + ': ' + e);
                }
            }
        } catch (FileNotFoundException e) {
            System.err.println('File not found: ' + filePath);
        } catch (IOException e) {
            System.err.println('IO error: ' + e.getMessage());
        }
    }
}

// Best Practices Summary:
// 1. Always use try-with-resources
// 2. Use BufferedReader/Writer for text (faster)
// 3. Use FileInputStream/OutputStream for binary
// 4. Check file existence and permissions before use
// 5. Validate file size before reading
// 6. Use appropriate buffer sizes
// 7. Handle specific exceptions (FileNotFoundException, etc.)
// 8. Close resources explicitly if not using try-with-resources
// 9. Log errors appropriately
// 10. Use Files API for Java 7+ applications
File Handling Best Practices:

1. Try-with-Resources:
try (BufferedReader br = new BufferedReader(
        new FileReader('file.txt'))) {
    // Auto-close
}

2. Check file properties:
if (file.exists() && file.canRead()) {
    // Process file
}

3. Use buffering for efficiency:
BufferedReader (text)
BufferedWriter (text)
ByteBuffer (binary)

4. Handle exceptions properly:
try {
    // File operations
} catch (FileNotFoundException e) {
    // File missing
} catch (IOException e) {
    // Other IO errors
}

5. Modern approach (Java 7+):
Files.readAllLines(Paths.get('file.txt'))
Files.write(path, content.getBytes())

Was this answer clear?