最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot打成jar后獲取classpath下文件失敗的解決方案

 更新時間:2021年08月11日 11:15:36   作者:chenshiying007  
這篇文章主要介紹了使用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下的文件實現(xiàn)文件下載?

怎么獲取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("模板文件下載成功");
    }

高高興興的啟動項目后發(fā)現(xiàn)還是找不到文件,錯誤日志:

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”目錄下),就發(fā)現(xiàn)并沒有這個文件在。

后面仔細想想這是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下看,發(fā)現(xiàn)有了這個文件了,同時也能獲取了。如果文件名為中文的話就會出現(xiàn)亂碼的情況。

怎么解決文件名中文亂碼?

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響應頭相關(guān)信息。

后面怎么改都亂碼,然后我就試著到瀏覽器中請求試試,結(jié)果發(fā)現(xiàn)只是postman的原因,只要文件名編碼跟返回內(nèi)容編碼一致("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);

到此全部結(jié)束!

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • IDEA之web項目導入jar包方式

    IDEA之web項目導入jar包方式

    這篇文章主要介紹了IDEA之web項目導入jar包方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • 集合框架(Collections Framework)詳解及代碼示例

    集合框架(Collections Framework)詳解及代碼示例

    這篇文章主要介紹了集合框架(Collections Framework)詳解及代碼示例,文章涉及集合數(shù)組的區(qū)別,collection接口,iterator迭代器,list接口及其用法,LinkedHashSet集合等有關(guān)內(nèi)容,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • springBoot controller,service,dao,mapper,model層的作用說明

    springBoot controller,service,dao,mapper,model層的作用說明

    這篇文章主要介紹了springBoot controller,service,dao,mapper,model層的作用說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • springbean的八種加載方式匯總

    springbean的八種加載方式匯總

    這篇文章主要介紹了springbean的八種加載方式,一種是XML方式聲明bean,使用@Component及其衍生注解@Controller?、@Service、@Repository定義bean,還有其他方法,本文給大家介紹的非常詳細,需要的朋友可以參考下
    2022-10-10
  • Java 事務詳解及簡單應用實例

    Java 事務詳解及簡單應用實例

    這篇文章主要介紹了Java 事務詳解及簡單應用實例的相關(guān)資料,java事務能夠保證數(shù)據(jù)的完整性和一致性,當然這是書本上的知識,具體如何應用這里舉例說明,需要的朋友可以參考下
    2016-12-12
  • SpringMVC 傳日期參數(shù)到后臺的實例講解

    SpringMVC 傳日期參數(shù)到后臺的實例講解

    下面小編就為大家分享一篇SpringMVC 傳日期參數(shù)到后臺的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2017-12-12
  • Java(JDK/Tomcat/Maven)運行環(huán)境配置及工具(idea/eclipse)安裝詳細教程

    Java(JDK/Tomcat/Maven)運行環(huán)境配置及工具(idea/eclipse)安裝詳細教程

    這篇文章主要介紹了Java(JDK/Tomcat/Maven)運行環(huán)境配置及工具(idea/eclipse)安裝,本文給大家介紹的非常想詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03
  • springboot的logback配置源碼解讀

    springboot的logback配置源碼解讀

    這篇文章主要為大家介紹了springboot的logback配置,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-11-11
  • Java語言實現(xiàn)掃雷游戲(2)

    Java語言實現(xiàn)掃雷游戲(2)

    這篇文章主要為大家詳細介紹了Java語言實現(xiàn)掃雷游戲第二部分代碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • Java使用poi-tl1.9.1生成Word文檔的技巧分享

    Java使用poi-tl1.9.1生成Word文檔的技巧分享

    本文將簡單介紹poi-tl的相關(guān)知識,通過一個實際的案例實踐,充分介紹如何利用poi-tl進行目標文檔的生成,同時分享幾個不同的office版本如何進行圖表生成的解決方案,需要的朋友可以參考下
    2023-09-09

最新評論

左贡县| 饶平县| 安顺市| 卢龙县| 乐亭县| 曲松县| 普安县| 辉县市| 海安县| 山阳县| 福海县| 贵南县| 五峰| 石阡县| 津市市| 滁州市| 五大连池市| 淮北市| 滨海县| 凉城县| 革吉县| 麻江县| 林甸县| 新乐市| 雷州市| 红河县| 扶风县| 昌都县| 青铜峡市| 苗栗县| 儋州市| 山阴县| 通许县| 延安市| 盐城市| 德庆县| 昌黎县| 温州市| 牟定县| 临洮县| 宿州市|