Here you can find the source of getInputStream(Class> cls, String path)
Parameter | Description |
---|---|
cls | this will generally be the class of the caller. |
path | should be the path of a resource on the classpath (e.g. "/models/en-sent.bin") or the path of a file on the local file system (e.g. "src/main/resources/models/en-sent.bin") |
Parameter | Description |
---|---|
IOException | if the path was not found as a URL, resource or file. |
public static InputStream getInputStream(Class<?> cls, String path) throws IOException
//package com.java2s; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; public class Main { /**/* w ww. ja v a 2 s. c om*/ * This method attempts to create an input stream from the given path by: * <ol> * <li>Trying to parse it as a URL</li> * <li>Trying to find it on the classpath, relative to the given class</li> * <li>Trying to find it as a file on the file system</li> * </ol> * * @param cls * this will generally be the class of the caller. * @param path * should be the path of a resource on the classpath (e.g. "/models/en-sent.bin") or the * path of a file on the local file system (e.g. "src/main/resources/models/en-sent.bin") * @return A newly opened InputStream. The caller is responsible for closing the stream. * @throws IOException * if the path was not found as a URL, resource or file. */ public static InputStream getInputStream(Class<?> cls, String path) throws IOException { InputStream inputStream; try { inputStream = new URL(path).openStream(); } catch (MalformedURLException e) { inputStream = cls.getResourceAsStream(path); if (inputStream == null) { try { inputStream = new FileInputStream(path); } catch (FileNotFoundException e1) { throw new IOException(String.format( "unable to find %s " + "as a resource on the classpath, as a url or as a file.", path)); } } } return new BufferedInputStream(inputStream); } }