如何从资源文件夹中获取文件作为文件?

flmtquvp  于 2021-07-09  发布在  Java
关注(0)|答案(4)|浏览(474)

如果存在,我想从资源文件夹中获取一个文件,如果不存在,我想在那里创建它。我想以文件的形式访问它。getresource()返回url时不起作用。getresourceasstream()提供了输入流,但是我不能在其中写入,或者我可以吗?

  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. public class Statistika {
  4. File file;
  5. public Statistika() {
  6. try {
  7. file = Statistika.class.getResourceAsStream("statistics.txt");
  8. } catch (FileNotFoundException e) {
  9. file = new File("statistics.txt");
  10. }
  11. }

如何做到这一点?

nbysray5

nbysray51#

尝试使用 Statistika.class.getClassLoader().getResource(filename); 如果它返回null,那么您可以创建新的文件/目录。
如果您从jar访问这个,那么使用 Statistika.class.getClassLoader().getResourceAsStream(filename); 希望它能解决你的问题。如果你发现任何困难,请告诉我。

cgh8pdjw

cgh8pdjw2#

不要这样做 file = new File("statistics.txt"); 在你的接球区。。只需做以下操作

  1. try {
  2. File file = new File("statistics.txt");
  3. InputStream fis = new FileInputStream(file);
  4. fis = Statistika.class.getResourceAsStream(file.getName());
  5. } catch (FileNotFoundException e) {
  6. }

这与文件是否存在无关。

dvtswwa3

dvtswwa33#

你试过这个吗?

  1. File f = new File(Statistika.class.getResource("resource.name").toURI());
  2. if (!f.isFile()){
  3. f.getParentFile().mkdirs();
  4. f.createNewFile();
  5. }
kfgdxczn

kfgdxczn4#

  1. File f = new File("statistics.txt");
  2. try {
  3. f.createNewFile();
  4. } catch (IOException ex) { }
  5. InputStream fis = new FileInputStream(f);

使用bufferedreader将内容插入到f引用的文件中。

相关问题