ResouceUtil.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package cn.com.qmth.am.utils;
  2. import java.io.BufferedReader;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.net.URL;
  6. import org.apache.commons.io.IOUtils;
  7. public class ResouceUtil {
  8. public static URL getUrl(String path) {
  9. try {
  10. ClassLoader classLoader = ResouceUtil.class.getClassLoader();
  11. URL url = classLoader.getResource(path);
  12. return url;
  13. } catch (Exception e) {
  14. throw new RuntimeException(e);
  15. }
  16. }
  17. public static InputStream getStream(String path) {
  18. try {
  19. ClassLoader classLoader = ResouceUtil.class.getClassLoader();
  20. URL url = classLoader.getResource(path);
  21. return url.openStream();
  22. } catch (Exception e) {
  23. throw new RuntimeException(e);
  24. }
  25. }
  26. public static String getContent(String path) {
  27. try {
  28. ClassLoader classLoader = ResouceUtil.class.getClassLoader();
  29. URL url = classLoader.getResource(path);
  30. return readFileContent(url.openStream());
  31. } catch (Exception e) {
  32. throw new RuntimeException(e);
  33. }
  34. }
  35. @SuppressWarnings("deprecation")
  36. private static String readFileContent(InputStream in) {
  37. StringBuilder content = new StringBuilder();
  38. InputStreamReader streamReader = null;
  39. BufferedReader bufferedReader = null;
  40. try {
  41. String encoding = "UTF-8";
  42. streamReader = new InputStreamReader(in, encoding);
  43. bufferedReader = new BufferedReader(streamReader);
  44. String line;
  45. while ((line = bufferedReader.readLine()) != null) {
  46. content.append(line);
  47. }
  48. } catch (Exception e) {
  49. throw new RuntimeException(e);
  50. } finally {
  51. IOUtils.closeQuietly(in);
  52. IOUtils.closeQuietly(streamReader);
  53. IOUtils.closeQuietly(bufferedReader);
  54. }
  55. return content.toString();
  56. }
  57. }