Skip to content

Instantly share code, notes, and snippets.

@itang
Created October 29, 2011 04:42
Show Gist options
  • Save itang/1324106 to your computer and use it in GitHub Desktop.
Save itang/1324106 to your computer and use it in GitHub Desktop.
package test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.Callable;
import api.Unchecked;
public class Test {
public static void main(String[] args) {
String fileContent = Unchecked.with(new Callable<String>() {
@Override
public String call() throws Exception {
return getFileContent("/home/itang/.bashrc");
}
});
System.out.println(fileContent);
try {
Unchecked.with(new Callable<String>() {
@Override
public String call() throws Exception {
return getFileContent("/home/itang/.bashrc_bad");
}
});
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
}
private static String getFileContent(String path) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
StringBuilder sb = new StringBuilder();
String lineSp = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
sb.append(line).append(lineSp);
}
return sb.toString();
}
}
package api;
import java.util.concurrent.Callable;
public class Unchecked {
public static <T> T with(Callable<T> call) {
try {
return call.call();
} catch (RuntimeException e) {
throw e;
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment