简体   繁体   English

Java如何将资源(内部文本文件)写出到目录中?

[英]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. 我有一个要存储在jar中的文件,该文件使用默认设置文件。 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. 使用getResourceAsStream访问资源。 Create a FileOutputStream for the file you wish to write. 为您要写入的文件创建FileOutputStream 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 . 请参阅与资源无关的位置访问

use "getResourceAsStream" 使用“ getResourceAsStream”

-> http://mindprod.com/jgloss/getresourceasstream.html -> http://mindprod.com/jgloss/getresourceasstream.html

given a resource that you want to write to a given Path path , then you can use: 给定resource ,你想要写一个给定Path path ,那么你可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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