一般我们在编写完Java程序中获取资源路径,在开发和调试期(未打包前),是没有问题的,但在打包后,由于资源(图片、配置文件等)都将打包到jar文件中,由于System中的“user.dir”属性发生了变化,会造成用绝对路径的方式无法找到jar文件中的资源文件。因为程序载入图片或文本文件时,使用以当前工作路径为基准的方式来指定文件和路径,而资源文件打在jar包中后程序无法通过绝对路径找到。因此可采用Java本身以类为基准的路径搜索方式。如下两种方式:
取得相对于包的根路径
Java Code 复制内容到剪贴板
1. String path = new File(FrameConfig.class.getResource("/").getFile())
2. .getAbsolutePath();
取得相对于包路径的流
Java Code 复制内容到剪贴板
1. Reader reader = new
2. class.getResourceAsStream("/res/uiConfig.xml"));
含有这种代码的程序在运行时,以类(类路径)为基准,而不依赖当前路径(System中的user.dir),
【注】:上面的路径“/res/uiConfig.xml”是相对于包的路径,如果写成“res/uiConfig.xml”,表示相对于类的路径:package/res/uiConfig.xml,这需要将图片和文本等文件的保存路径,和程序中指定的路径两者保持一致。
读取jar包中根Element(dom4j)
Java Code 复制内容到剪贴板
1. private static
2. null;
3. null;
4. try
5. new
6. class.getResourceAsStream(path));
7. new
8. catch
9. e.printStackTrace();
10. finally
11. closeStream(reader);
12. }
13. return
14. }
15.
16. private static void
17. if (stream != null)
18. try
19. stream.close();
20. catch
21. e.printStackTrace();
22. }
23. }
24.
25. public static void
26. "/res/uiConfig.xml");
27. }
读取jar包中根Element(jdom)
Java Code 复制内容到剪贴板
1. private static
2. null;
3. null;
4. try
5. new
6. class.getResourceAsStream(path));
7. new
8. catch
9. e.printStackTrace();
10. finally
11. closeStream(reader);
12. }
13. return
14. }
读取jar包中国际化资源文件
Java Code 复制内容到剪贴板
1. ResourceBundle resources = ResourceBundle.getBundle(
2. "res.i18n", Locale.getDefault());
3. // 取得对应的值
4. String value = resources.getString(key);
读取jar包中的图片资源
Java Code 复制内容到剪贴板
1. public static
2. null;
3. null;
4. try
5. class.getResourceAsStream("/res/images/"
6. + imageName);
7. new
8. byte buffer[] = new byte[1024];
9. int len = 0;
10. while ((len = inputStream.read(buffer)) != -1)
11. 0, len);
12. return
13. outputStream.toByteArray());
14. catch
15. th.printStackTrace();
16. finally
17. closeStream(inputStream);
18. closeStream(outputStream);
19. }
20. return null;
21. }
22.
23. public static void
24. "add.gif");
25. }