ByteArrayResource:通过byte 数组构建Resource
public class ByteArrayResource extends AbstractResource { private final byte[] byteArray; private final String description; /** * This implementation returns a ByteArrayInputStream for the * underlying byte array. * @see java.io.ByteArrayInputStream */ public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(this.byteArray); } }
FileSystemResource:文件资源,可读写
public class FileSystemResource extends AbstractResource implements WritableResource { private final File file; private final String path; /** * This implementation opens a FileInputStream for the underlying file. * @see java.io.FileInputStream */ public InputStream getInputStream() throws IOException { return new FileInputStream(this.file); } /** * This implementation opens a FileOutputStream for the underlying file. * WritableResouce接口方法 * @see java.io.FileOutputStream */ public OutputStream getOutputStream() throws IOException { return new FileOutputStream(this.file); } /** * Create a new FileSystemResource from a file path. *Note: When building relative resources via {@link #createRelative}, * it makes a difference whether the specified resource base path here * ends with a slash or not. In the case of "C:/dir1/", relative paths * will be built underneath that root: e.g. relative path "dir2" -> * "C:/dir1/dir2". In the case of "C:/dir1", relative paths will apply * at the same directory level: relative path "dir2" -> "C:/dir2". * @param path a file path */ public FileSystemResource(String path) { Assert.notNull(path, "Path must not be null"); this.file = new File(path); this.path = StringUtils.cleanPath(path);//路径处理:如前缀,..等 } }
ClassPathResource:
通过给定的classLoader或者class加载资源文件
public class ClassPathResource extends AbstractFileResolvingResource { private final String path; private ClassLoader classLoader; private Class> clazz; public ClassPathResource(String path, ClassLoader classLoader) { Assert.notNull(path, "Path must not be null"); String pathToUse = StringUtils.cleanPath(path); if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } this.path = pathToUse; //classLoader为空,则初始化当前线程的classLoader Thread.currentThread().getContextClassLoader(); this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader()); } }
资源文件方式:
/** * This implementation opens an InputStream for the given class path resource. * @see java.lang.ClassLoader#getResourceAsStream(String) * @see java.lang.Class#getResourceAsStream(String) */ public InputStream getInputStream() throws IOException { InputStream is; if (this.clazz != null) { is = this.clazz.getResourceAsStream(this.path); } else { is = this.classLoader.getResourceAsStream(this.path); } if (is == null) { throw new FileNotFoundException( getDescription() + " cannot be opened because it does not exist"); } return is; }