com.jcraft.jsch.JSchException: java.io.FileNotFoundException: file:\D:\development\ideaProjects\salary-card\target\salary-card-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes!\keystore\login_id_rsa (文件名、目錄名或卷標語法不正確。)
Caused by: java.io.FileNotFoundException: file:\D:\development\ideaProjects\salary-card\target\salary-card-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes!\keystore\login_id_rsa (文件名、目錄名或卷標語法不正確。)
問題:
資源未獲取到,開發環境沒問題,測試環境有問題;
原因:
經排查,發現是因為在打完jar包后運行,jar包中無法獲取對應目錄的資源文件;
這主要是因為jar包是一個單獨的文件而不是文件夾,不能通過“file:\D:\development\ideaProjects\salary-card\target\salary-card-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes!\keystore\login_id_rsa”定位jar包內的資源。
解決:
所以綜上所述,我們在通過jar包來訪問的話,不要使用getResource或getFile方法來訪問了,使用resource.getInputStream() 或getResourceAsStream()方法,通過流的形式來訪問資源是可以的;
例:
InputStream is=this.getClass().getResourceAsStream("keystore/login_id_rsa");
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String s="";
while((s=br.readLine())!=null)
System.out.println(s);
或
Resource resource = new ClassPathResource("keystore/login_id_rsa"); InputStream inputStream = resource.getInputStream(); ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); byte[] buff = new byte[100]; int rc = 0; while ((rc = inputStream.read(buff, 0, 100)) > 0) { swapStream.write(buff, 0, rc); }