我如何在Spring Boot中将文件写入类路径?

我正在尝试将序列化的目标文件写入我的类路径,该文件稍后将用于读取目的。我写了下面的代码,

FileOutputStream fos = new FileOutputStream("src/main/resources/ListOfIotcontentObjects");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(fileList);

So while building the project with mvn clean package its creating the executable .jar without any exception, but when i tried to run the .jar it's saying (The system cannot find the path specified)

我不明白这里出了什么问题以及如何使它正常工作?提前致谢。

评论
xnemo
xnemo
  1. try getting the resource folder from the classloader
  2. and then create the new file and store the contents

    try {
      String path = 
              Thread.currentThread().getContextClassLoader()
              .getResource(".").getFile() + "/ListOfIotcontentObjects";
    
            File file = new File(path);
            if (file.createNewFile()){
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(fileList);
            }
    } catch (IOException e) {
           e.printStackTrace();
    }
    
点赞
评论