若是在jar中須要訪問jar包內部的某個資源文件,能夠用class.getResourceAsStream(文件路徑)獲取文件內容。java
假設文件路徑是project/src/com/zh/resource, code以下:app
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException;public class test { public static void main(String[] args) { StringBuffer fileStrBuffer = loadFile("/com/zh/resource/test.txt"); if(fileStrBuffer!=null) { System.out.print(fileStrBuffer); } } /** * Load the specified file. * * @return The buffer to store file content. */ private static StringBuffer loadFile(String file) { StringBuffer buffer = new StringBuffer(); InputStream is = test.class.getResourceAsStream(file); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(is, "utf-8")); String tempString = null; while ((tempString = reader.readLine()) != null) { buffer.append(tempString); } } catch (UnsupportedEncodingException e) { buffer = null; } catch (IOException e) { buffer = null; } finally { try { is.close(); } catch (IOException e) { } } return buffer; } }
結果:spa
xxxxx{0}xxxxx{1}xxxxxxxx{2}xxxxxx