How to copy file inside jar to outside the jar?

后端 未结 9 957
深忆病人
深忆病人 2020-11-27 03:37

I want to copy a file from a jar. The file that I am copying is going to be copied outside the working directory. I have done some tests and all methods I try end up with 0

9条回答
  •  佛祖请我去吃肉
    2020-11-27 04:20

    To copy a file from your jar, to the outside, you need to use the following approach:

    1. Get a InputStream to a the file inside your jar file using getResourceAsStream()
    2. We open our target file using a FileOutputStream
    3. We copy bytes from the input to the output stream
    4. We close our streams to prevent resource leaks

    Example code that also contains a variable to not replace the existing values:

    public File saveResource(String name) throws IOException {
        return saveResource(name, true);
    }
    
    public File saveResource(String name, boolean replace) throws IOException {
        return saveResource(new File("."), name, replace)
    }
    
    public File saveResource(File outputDirectory, String name) throws IOException {
        return saveResource(outputDirectory, name, true);
    }
    
    public File saveResource(File outputDirectory, String name, boolean replace)
           throws IOException {
        File out = new File(outputDirectory, name);
        if (!replace && out.exists()) 
            return out;
        // Step 1:
        InputStream resource = this.getClass().getResourceAsStream(name);
        if (resource == null)
           throw new FileNotFoundException(name + " (resource not found)");
        // Step 2 and automatic step 4
        try(InputStream in = resource;
            OutputStream writer = new BufferedOutputStream(
                new FileOutputStream(out))) {
             // Step 3
             byte[] buffer = new byte[1024 * 4];
             int length;
             while((length = in.read(buffer)) >= 0) {
                 writer.write(buffer, 0, length);
             }
         }
         return out;
    }
    

提交回复
热议问题