springboot打成jar后获取classpath下文件失败的解决方案

springboot打成jar后获取classpath下文件

代码如下:

ClassPathResource resource = new ClassPathResource("app.keystore");
File file = resource.getFile();
FileUtils.readLines(file).forEach(System.out::println);

解决方式如下:

1. Spring framework

String data = "";
ClassPathResource cpr = new ClassPathResource("static/file.txt");
try {
    byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
    data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
    LOG.warn("IOException", e);
}

2.use a file

ClassPathResource classPathResource = new ClassPathResource("static/something.txt");
InputStream inputStream = classPathResource.getInputStream();
File somethingFile = File.createTempFile("test", ".txt");
try {
    FileUtils.copyInputStreamToFile(inputStream, somethingFile);
} finally {
    IOUtils.closeQuietly(inputStream);
}
Resource resource = new ClassPathResource("data.sql");
BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
reader.lines().forEach(System.out::println);
String content = new ClassPathResourceReader("data.sql").getContent();
@Value("${resourceLoader.file.location}")
    @Setter
    private String location;
    private final ResourceLoader resourceLoader;
public void readallfilesfromresources() {
       Resource[] resources;

        try {
            resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources("classpath:" + location + "/*.json");
            for (int i = 0; i < resources.length; i++) {
                try {
                InputStream is = resources[i].getInputStream();
                byte[] encoded = IOUtils.toByteArray(is);
                String content = new String(encoded, Charset.forName("UTF-8"));
                }
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
}

springboot-项目获取resources下文件碰到的问题(classPath下找不到文件和文件名乱码)

项目是spring-boot + spring-cloud 并使用maven 管理依赖。在springboot+maven项目下怎么读取resources下的文件实现文件下载?

怎么获取resources目录下的文件?(相对路径)

方法一:

File sourceFile = ResourceUtils.getFile("classpath:templateFile/test.xlsx"); //这种方法在linux下无法工作

方法二:

Resource resource = new ClassPathResource("templateFile/test.xlsx"); File sourceFile = resource.getFile();

我使用的是第二种。

@PostMapping("/downloadTemplateFile")
    public JSONData downloadTemplateFile(HttpServletResponse response) {
        String filePath = "templateFile/test.xlsx";
        Resource resource = new ClassPathResource(filePath);//用来读取resources下的文件
        InputStream is = null;
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            File file = resource.getFile();
            if (!file.exists()) {
                return new JSONData(false,"模板文件不存在");
            }
            is = new FileInputStream(file);
            os = response.getOutputStream();
            bis = new BufferedInputStream(is);
            //设置响应头信息
            response.setCharacterEncoding("UTF-8");
            this.response.setContentType("application/octet-stream; charset=UTF-8");
            StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");
            String fileName = new String(file.getName().getBytes(), "utf-8");
            contentDisposition.append(fileName).append("\"");
            this.response.setHeader("Content-disposition", contentDisposition.toString());
            //边读边写
            byte[] buffer = new byte[500];
            int i;
            while ((i = bis.read(buffer)) != -1) {
                os.write(buffer, 0, i);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return new JSONData(false,"模板文件不存在");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os != null) os.close();
                if(bis != null) bis.close();
                if(is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new JSONData("模板文件下载成功");
    }

高高兴兴的启动项目后发现还是找不到文件,错误日志:

java.io.FileNotFoundException: class path resource [templateFile/test.xlsx] cannot be resolved to URL because it does not exist
    at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:195)
    at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:129)
    at com.citycloud.parking.support.controller.operate.OperateBusinessUserController.downloadTemplateFile(OperateBusinessUserController.java:215)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:158)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:126)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:111)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

因为我知道Resource resource = new ClassPathResource("templateFile/test.xlsx");就是到classPath*(注意这里有个*)下去找,然后就去项目本地的目录下找classPath下是否有这个文件(maven的classPath在 “target\classes”目录下),就发现并没有这个文件在。

后面仔细想想这是Maven项目啊,所以就找pom.xml文件去看看,突然想起:springboot的maven默认只会加载classPath同级目录下文件(配置那些),其他的需要配置<resources>标签:

<build>
  <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <!--是否替换资源中的属性-->
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.yml</include>
          <include>**/Dockerfile</include>
          <include>**/*.xlsx</include>
        </includes>
        <!--是否替换资源中的属性-->
        <filtering>false</filtering>
      </resource>
  </resources>
</build>

重新启动,再到classPath下看,发现有了这个文件了,同时也能获取了。如果文件名为中文的话就会出现乱码的情况。

怎么解决文件名中文乱码?

Access-Control-Allow-Origin →*
Access-Control-Allow-Credentials →true
Access-Control-Allow-Headers →accessToken,Access-Control-Allow-Origin,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers
Access-Control-Allow-Methods →POST,GET,PUT,PATCH,DELETE,OPTIONS,HEAD
Access-Control-Max-Age →360
Content-disposition →attachment; filename="????????-??????????.xlsx"
Content-Type →application/octet-stream;charset=UTF-8
Transfer-Encoding →chunked
Date →Fri, 19 Apr 2019 06:47:34 GMT

上面是使用postman测试中文乱码response响应头相关信息。

后面怎么改都乱码,然后我就试着到浏览器中请求试试,结果发现只是postman的原因,只要文件名编码跟返回内容编码一致("Content-disposition"和“ContentType”)就行:

this.response.setContentType("application/octet-stream; charset=iso-8859-1");
StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");
String fileName = file.getName();
contentDisposition.append(fileName).append("\"");
//设置文件名编码
String contentDispositionStr = new String(contentDisposition.toString().getBytes(), "iso-8859-1");
this.response.setHeader("Content-disposition", contentDispositionStr);

到此全部结束!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • springboot读取文件,打成jar包后访问不到的解决

    springboot读取文件,打成jar包后访问不到 最新开发出现一种情况,springboot打成jar包后读取不到文件,原因是打包之后,文件的虚拟路径是无效的,只能通过流去读取. 文件在resources下 public void test() { List<String> names = new ArrayList<>(); InputStreamReader read = null; try { ClassPathResource resource = new ClassP

  • 解决java项目jar打包后读取文件失败的问题

    java项目jar打包后读取文件失败 在本地项目读取文件时 this.getClass().getClassLoader().getResource("").getPath()+fileName this.getClass().getResource("/filename").getPath() 都是可以成功的 但是jar打包后上面方式读取文件时 会变成 jar!filename 这样的形式去读取文件,这样是读取不到文件的 可以使用 Test.class.getRe

  • 解决SpringBoot打成jar运行后无法读取resources里的文件问题

    开发一个word替换功能时,因替换其中的内容功能需要 word 模版,就把 word_replace_tpl.docx 模版文件放到 resources 下 在开发环境中通过下面方法能读取word_replace_tpl.docx文件,但是打成jar包在 linux下运行后无法找到文件了 File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/office_template/xxx.docx&q

  • 关于Springboot打成JAR包后读取外部配置文件的问题

    Springboot的默认配置文件为:application.properties或者是application.yml 如果这两个配置文件都存在,不冲突的话,就互相补充.冲突的话,则properties优先级高. 当我们使用IDEA创建出一个Springboot项目上时,配置文件默认出现在classpath(也就是项目里的resources)目录下. Springboot的application.properties配置文件的加载路径优先级(从高到低): 工程根目录:./config/ 工程根目

  • springboot打成jar后获取classpath下文件失败的解决方案

    springboot打成jar后获取classpath下文件 代码如下: ClassPathResource resource = new ClassPathResource("app.keystore"); File file = resource.getFile(); FileUtils.readLines(file).forEach(System.out::println); 解决方式如下: 1. Spring framework String data = "&quo

  • springboot打成jar后无法读取根路径和文件的解决

    目录 springboot打成jar后无法读取根路径和文件 springboot打jar找不到资源文件 springboot打成jar后无法读取根路径和文件 ClassLoader.getSystemResourceAsStream(authenticationFileName) PropertiesUtils.class.getClass().getResourceAsStream("/authentication.properties") 未打包时都可以获取到根路径和文件 打包后报

  • SpringBoot打jar包遇到的xml文件丢失的解决方案

    目录 SpringBoot打jar包遇到的xml文件丢失 在pom.xml的build标签中添加如下内容 SpringBoot打jar包遇到的一些问题 1.访问不到jsp页面 1.1 jar包中没有jsp文件,报404错误 1.2 还是访问不到页面,但不报错,一直在加载 1.3 此时若还报错 SpringBoot打jar包遇到的xml文件丢失 在pom.xml的build标签中添加如下内容 指定资源路径 <resources> <resource> <directory>

  • 解决spring-boot 打成jar包后 启动时指定参数无效的问题

    spring-boot打成jar启动时指定参数无效 今天后台项目进行修改,使用spring.profiles来指定启动时使用的配置文件. 在项目中添加好配置文件后使用java -jar .\base-exec.jar --spring.profiles.active=dev --server.port=9121启动时参数注入不进去. 检查配置文件书写的规则,这里把规则说一下 我们在开发Spring Boot应用时,通常同一套程序会被应用和安装到几个不同的环境,比如:开发.测试.生产等.其中每个环

  • 使用Springboot打成jar包thymeleaf的问题

    目录 Springboot打成jar包thymeleaf 1.使用springboot打成jar包 2. controller的书写 springboot + thymeleaf jar包运行就报错 你应该知道这样排错 1.静态文件错误 2.controller层返回页面错误 3.小结一下 Springboot打成jar包thymeleaf 1.使用springboot打成jar包 需要在maven中添加插件 <build> <plugins> <plugin> <

  • java 使用idea将工程打成jar并创建成exe文件类型执行的方法详解

    第一部分: 使用idea 打包工程jar 1.准备好一份 开发好的 可执行的 含有main方法的 工程. 例如:我随便写的main方法 public static void main(String[] args) throws IOException { Properties properties = System.getProperties(); String osName = properties.getProperty("os.name"); System.out.println

  • 解决tomcat发布工程后,WEB-INF/classes下文件不编译的问题

    今天部署项目到tomcat,发布完后,启动tomcat,报class not found: 临时找了个解决方案,由于项目是copy过来的,于是就将原来项目的classes下面编译好的class文件也一并拷过来了:但是治标不治本: 后来在我修改代码的时候,重新发布到tomcat,发现新写的代码还是没有自动编译:classes下面还是没有class文件: 于是找解决方法:我是按照下面操作成功的: 1)在java build path下面删除原来的jre,重新导入jre: 2)删掉所有引用的jar包,

  • python获取Linux下文件版本信息、公司名和产品名的方法

    本文实例讲述了python获取Linux下文件版本信息.公司名和产品名的方法,分享给大家供大家参考.具体如下: 区别于前文所述.本例是在linux下得到文件版本信息,主要是通过pefile模块解析文件 中的字符串得到的.代码如下: def _get_company_and_product(self, file_path): """ Read all properties of the given file return them as a dictionary. @retur

随机推荐