Subjects

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

What is try-with-resources statement and why is it important for file I/O? try-with-resources statement क्या है और file I/O में क्यों महत्वपूर्ण है?

Answer

Try-with-resources automatically closes resources (files, streams) even if exceptions occur. It prevents resource leaks and makes code cleaner. Available since Java 7.

// OLD way (manual close needed)
FileReader reader = null;
try {
    reader = new FileReader('file.txt');
    // Read from file
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (reader != null) {
        try {
            reader.close();  // Easy to forget!
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// NEW way (Java 7+) - try-with-resources
try (FileReader reader = new FileReader('file.txt')) {
    int ch;
    while ((ch = reader.read()) != -1) {
        System.out.print((char) ch);
    }
} catch (IOException e) {
    e.printStackTrace();
}
// Automatically closes reader

// Multiple resources
try (FileReader fr = new FileReader('input.txt');
     FileWriter fw = new FileWriter('output.txt')) {
    int ch;
    while ((ch = fr.read()) != -1) {
        fw.write(ch);
    }
} catch (IOException e) {
    e.printStackTrace();
}
// Both files automatically closed

// Custom AutoCloseable class
public class DatabaseConnection implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println('Connection closed');
    }
    
    public void query(String sql) {
        System.out.println('Executing: ' + sql);
    }
}

// Using custom AutoCloseable
try (DatabaseConnection db = new DatabaseConnection()) {
    db.query('SELECT * FROM users');
} catch (Exception e) {
    e.printStackTrace();
}
// Connection automatically closed

// Benefits:
// 1. Automatic resource cleanup
// 2. No resource leaks
// 3. Exception handling during close
// 4. Cleaner code
// 5. Safe concurrent access
Try-with-Resources:

Syntax:
try (ResourceType resource = new Resource()) {
    // Use resource
} catch (Exception e) {
    // Handle exception
}

Benefits:
1. Auto-close resources
2. Prevents memory leaks
3. Exception-safe
4. Clean code

Multiple resources:
try (R1 r1 = new R1();
     R2 r2 = new R2()) {
    // Use r1 and r2
}

Was this answer clear?