Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java Example: Try-with-resources Statement http://www.chankok.com/java-try-with-resources/
package com.chankok.io;
import java.io.FileReader;
import java.io.IOException;
public class Java6ResourceManagementExample {
public static void main(String[] args) {
FileReader fr = null;
try {
// Create an input stream
fr = new FileReader("C:\\test1.txt");
int data;
// Read a character and print it on console one by one
while ((data = fr.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// Close the input stream
if (fr != null) fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.chankok.io;
public class MyResource implements AutoCloseable {
// Override the close() method
@Override
public void close() throws Exception {
System.out.println("MyResource - close()");
// ...
}
// Implement custom method
public void myMethod() {
System.out.println("MyResource - myMethod()");
// ...
}
}
package com.chankok.io;
public class TryWithResourcesCustomResourceExample {
public static void main(String[] args) {
// Create a resource
try (MyResource myResource = new MyResource()) {
// Run the resource method
myResource.myMethod();
// Close the resource automatically when exit the try block
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.chankok.io;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesMutipleResourcesExample {
public static void main(String[] args) {
// Create 2 input streams
try (FileReader fr1 = new FileReader("D:\\test3.txt");
FileReader fr2 = new FileReader("D:\\test4.txt")) {
int data;
// Read a character and print it on console one by one
while ((data = fr1.read()) != -1) {
System.out.print((char) data);
}
// Print new line on console
System.out.println();
// Read a character and print it on console one by one
while ((data = fr2.read()) != -1) {
System.out.print((char) data);
}
// Close 2 input streams automatically when exit the try block
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.chankok.io;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesSingleResourceExample {
public static void main(String[] args) {
// Create an input stream
try (FileReader fr = new FileReader("C:\\test2.txt")) {
int data;
// Read a character and print it on console one by one
while ((data = fr.read()) != -1) {
System.out.print((char) data);
}
// Close input stream automatically when exit the try block
} catch (IOException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment