Upload a file located inside a jar

Viewed 143

I'm trying to upload a file located inside a jar. When I upload the file normally it works fine (which is expected because the file is on the file system) but when I package a jar with the file located inside it doesn't work. I've tried to use:

this.getClass().getClassLoader().getResource("big_bird.txt") //doesn't work

new File("big_bird.txt".toURI()) //doesn't work

this.getClass().getClassLoader().getResourceAsStream("big_bird.txt") //kinda work as in I see the path but I can't get the file

I need to be able to grab the file and upload it all while its inside the jar so can anyone give me some insight into how this can be done?

1 Answers
  1. Read the file as a stream from the jar

InputStream in = getClass().getResourceAsStream("big_bird.txt");

  1. Create a temp file

File tempFile = File.createTempFile("big_bird", "txt");

  1. Write input stream to temp file
try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
    int read;
    byte[] bytes = new byte[1024];
    while ((read = in.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
}
  1. Now you can use/upload tempFile
Related