第一种:
public static InputStream openStream(String resource) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream stream = classLoader.getResourceAsStream(resource);
if (stream == null) {
stream = StreamHelper.class.getClassLoader().getResourceAsStream(resource);
}
return stream;
}
第二种:
public static InputStream getStreamFromFile(File file) throws Exception {
InputStream stream = null;
try {
if (!file.exists()) {
throw new Exception("file " + file + " doesn't exist");
}
if (file.isDirectory()) {
throw new Exception("file " + file + " is a directory");
}
stream = new FileInputStream(file);
} catch (Exception e) {
throw new Exception("couldn't access file " + file + ": " + e.getMessage());
}
return stream;
}