读取jar包中文件

1、 得到jar加载路径App为jar中类名称java

  1. 第一种:jvm

    String path = App.class.getProtectionDomain().getCodeSource().getLocation().getPath();
     若是有中文;
     path = java.net.URLDecoder.decode(path, "UTF-8");
  2. 第二种:.net

    String path2 = PetController.class.getProtectionDomain().getCodeSource().getLocation().getFile();
  3. 第三种:(jvm实现)code

    String javaPath = System.getProperty("java.class.path");
  4. 获取分割符,好比加载了多个jar就须要分割资源

    System.out.println(System.getProperty("path.separator") + "path.separator");
         int firstIndex = path.lastIndexOf(System.getProperty("path.separator")) + 1;
         int lastIndex = path.lastIndexOf(File.separator) + 1;
         path = path.substring(firstIndex, lastIndex);
  5. 加载资源路径下文件/UI/background.jpg是从项目根路径开始的字符串

    java.net.URL fileURL = App.class.getResource("/UI/background.jpg");
         System.out.println( fileURL.getPath());
         InputStream ins = fileURL.openStream();
  6. 写到jar包外的绝对路径get

    OutputStream outs = new FileOutputStream("/Users/heliming/IdeaProjects/dm8/src/main/resources/UI/2.jpg");
    
         byte[] bytess = new byte[2048];
         //接受读取的内容(n就表明的相关数据,只不过是数字的形式)
         int ns = -1;
         //循环取出数据
         while ((ns = ins.read(bytess, 0, bytess.length)) != -1) {
             //转换成字符串
             //写入相关文件
             outs.write(bytess, 0, ns);
         }
  7. 读取项目根路径string

    InputStream in = App.class.getResourceAsStream("/UI/background.txt");
         byte[] bytes = new byte[2048];
         //接受读取的内容(n就表明的相关数据,只不过是数字的形式)
         int n = -1;
         //循环取出数据
         while ((n = in.read(bytes, 0, bytes.length)) != -1) {
             //转换成字符串
             String str = new String(bytes, 0, n, "UTF-8"); //这里能够实现字节到字符串的转换,比较实用
  8. 直接输出it

    System.out.println(str);
         }
    
         in.close();
相关文章
相关标签/搜索