Created
October 29, 2011 04:42
-
-
Save itang/1324106 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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