項目打包成jar包發布,程序中無法讀取靜態文件


在war包中可以通過以下方式來獲取文件,如下:

public class FilePathTest {

    public static void main (String[] args) {
        FileReader reader = null;
        try {
            // 方法一:通過文件全路徑獲取文件
            String path = Thread.currentThread().getContextClassLoader().getResource("static/test.txt").getFile();
//            String path = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX +"static/test.txt").getPath();
//            String path = ResourceUtils.getURL("classpath:static/test.txt").getPath();
//          // 輸出結果  /C:/projects/practice/target/classes/static/test.txt
            System.out.println(path);
//            File file = new File(path);
            //  方法二:通過相對路徑直接獲取文件
//            File file = ResourceUtils.getFile("classpath:static/test.txt");
            ClassPathResource resource = new ClassPathResource("static/test.txt");
            File file = resource.getFile();
            reader = new FileReader(file);
            char[] bytes = new char[21704];
            reader.read(bytes);
            StringBuffer sb = new StringBuffer();
            sb.append(bytes);
            // 輸出結果  哈哈,這是一個測試文件 
            System.out.println(sb.toString());
//            String content = new String(bytes);
//            // 輸出結果  哈哈,這是一個測試文件
//            System.out.println(content);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

問題來了,上圖的獲取方式中有一個共同點:都是根據文件地址來獲取文件對象。該文件地址都是編譯之后的文件目錄,在war包中可以根據該地址獲取文件,但是,當打包成JAR包時,無法通過該地址查找到文件對象,那么在JAR包中,如何讀取靜態文件呢?

 

在jar包中必須通過流的方式來讀取文件

解決方案一:

OutputStream outputStream = null;
InputStream inputStream = null;

ClassPathResource resource = new ClassPathResource("static/test.xls");
File test= new File("D://test.txt"); 

int len;

byte[] buf = new byte[1024];

try {
  outputStream = new FileOutputStream(test);

  inputStream =
new FileInputStream(resource.getInputStream());
  while ((len = inputStream.read(buf))>0) { 
    outputStream.write(buf,0,len);
  }
}catch (IOException io) {
   e.printStackTrace(); 
 } finally { 
    try {
      outputStream.close();
      inputStream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
 }

 

不獲取 java.io.File 對象,而是直接獲取輸入流:

Resource resource = new ClassPathResource("static/test.xls");
BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));


說明:構造得到 resource 對象之后直接獲取其輸入流 resource.getInputStream()。

 

 

解決方案二:

使用this.getClass().getClassLoader().getResourceAsStream();這種方式獲取文件的流數據

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("static/test.xls");

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM