1. 一般maven会将spring工程编译到target文件夹下,/target/classes就是其根目录。而src/main/resources下的文件被复制到了这个classes文件夹下。
2. maven会将src/test/java文件夹下的代码编译到target/test-classes文件夹下。同样的,如果src/test/resources下有资源文件的话,就复制到target/test-classes文件夹下。
测试代码运行时,优先使用test-classes文件夹下的资源文件,如果不存在,再使用classes文件夹下的资源文件。
前两种底层代码都是通过类加载器读取流
1. 使用org.springframework.core.io.ClassPathResource读取,开发环境和生产环境(Linux下jar包运行读取)都能读取。
Resource resource=new ClassPathResource("3.png"); InputStream fis = resource.getInputStream(); OutputStream fos=new FileOutputStream("E://3.png"); int len=0; byte[] buf=new byte[1024]; while((len=fis.read(buf,0,buf.length))!=-1){ fos.write(buf,0,len); } fos.close(); fis.close();2. 使用流的方式来读取,两种方式,开发环境和生产环境(Linux下jar包运行读取)都能读取。
方式一:
InputStream fis = this.getClass().getResourceAsStream("/3.png"); OutputStream fos=new FileOutputStream("E://3.png"); int len=0; byte[] buf=new byte[1024]; while((len=fis.read(buf,0,buf.length))!=-1){ fos.write(buf,0,len); } fos.close(); fis.close();方式二:
InputStream fis = Thread.currentThread().getContextClassLoader().getResourceAsStream("/3.png"); OutputStream fos=new FileOutputStream("E://3.png"); int len=0; byte[] buf=new byte[1024]; while((len=fis.read(buf,0,buf.length))!=-1){ fos.write(buf,0,len); } fos.close(); fis.close();3. 使用org.springframework.core.io.ResourceLoader 读取,开发环境和生产环境(Linux下jar包运行读取)都能读取。
@Autowired ResourceLoader resourceLoader; @Test public void resourceLoaderTest() throws IOException { Resource resource = resourceLoader.getResource("classpath:3.png"); InputStream fis = resource.getInputStream(); OutputStream fos=new FileOutputStream("E://3.png"); int len=0; byte[] buf=new byte[1024]; while((len=fis.read(buf,0,buf.length))!=-1){ fos.write(buf,0,len); } fos.close(); fis.close(); }4. 使用File file=new File(“src/main/resources/file.txt”); 读取,只能在开发环境中读取,不能再生产环境中读取(Linux下jar包运行读取)。
File file=new File("src/main/resources/3.png"); InputStream fis=new FileInputStream(file); OutputStream fos=new FileOutputStream("E://3.png"); int len=0; byte[] buf=new byte[1024]; while ((len=fis.read(buf,0,buf.length))!=-1){ fos.write(buf,0,len); System.out.println("---"); } fos.close(); fis.close();5. 使用org.springframework.util.ResourceUtils 读取,只能在开发环境中读取,不能再生产环境中读取(Linux下jar包运行读取)。
File file = ResourceUtils.getFile("src/main/resources/3.png"); InputStream fis=new FileInputStream(file); OutputStream fos=new FileOutputStream("E://3.png"); int len=0; byte[] buf=new byte[1024]; while((len=fis.read(buf,0,buf.length))!=-1){ fos.write(buf,0,len); } fos.close(); fis.close();