简体   繁体   中英

Java How do I write a resource (internal text file) out to a directory?

I have a file I'm storing within my jar that I use a default setting file. I wish to write this file out to a user defined path. How do I write it out? This file that I'm trying to write out is in the same location as my class files that will be writing this file

Use getResourceAsStream to access the resource. Create a FileOutputStream for the file you wish to write. Read from one stream and write to the other. Preferably, use buffering, and don't forget to close your streams when you're done.

See Location-Independent Access to Resources .

given a resource that you want to write to a given Path path , then you can use:

try(InputStream is = this.getClass().getResourceAsStream(resource)){
    Files.copy(is, path);
} catch (Exception e){
    throw new RuntimeException(e);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM