How to get a path to a resource in a Java JAR file

前端 未结 16 2311
时光说笑
时光说笑 2020-11-22 09:23

I am trying to get a path to a Resource but I have had no luck.

This works (both in IDE and with the JAR) but this way I can\'t get a path to a file, only the file

16条回答
  •  野性不改
    2020-11-22 09:42

    follow code!

    /src/main/resources/file

    streamToFile(getClass().getClassLoader().getResourceAsStream("file"))
    
    public static File streamToFile(InputStream in) {
        if (in == null) {
            return null;
        }
    
        try {
            File f = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
            f.deleteOnExit();
    
            FileOutputStream out = new FileOutputStream(f);
            byte[] buffer = new byte[1024];
    
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
    
            return f;
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
            return null;
        }
    }
    

提交回复
热议问题