如何保证springboot项目打包成jar文件还可以获取resources下的temp文件夹下的文件门诊登记本.xls
时间: 2024-04-16 22:24:08 浏览: 156
在 Spring Boot 项目中,如果您希望在打包成 JAR 文件后仍然能够获取到 `resources` 下的 `temp` 文件夹中的文件,可以使用 `ClassPathResource` 的方式来读取该文件。
首先,确保 `temp` 文件夹位于 `resources` 文件夹下。然后,您可以按照以下方式获取该文件:
```java
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class ResourceExample {
public static void main(String[] args) {
String fileName = "temp/门诊登记本.xls";
try {
// 使用 ClassPathResource 获取 resources 文件夹下的文件
Resource resource = new ClassPathResource(fileName);
InputStream inputStream = resource.getInputStream();
// 指定临时目录或其他目录来保存文件
Path tempFile = Files.createTempFile("temp-", ".xls");
Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
// 获取文件的绝对路径
String absolutePath = tempFile.toAbsolutePath().toString();
System.out.println("Absolute Path: " + absolutePath);
} catch (IOException e) {
// 异常处理
}
}
}
```
在上面的示例中,我们获取了 `temp/门诊登记本.xls` 文件的输入流,并将其保存到临时目录中。通过 `Files.createTempFile()` 方法创建临时文件,并使用 `Files.copy()` 方法将输入流复制到临时文件中。
最后,使用 `tempFile.toAbsolutePath().toString()` 获取文件的绝对路径。
当您运行打包后的 JAR 文件时,它将仍然能够读取 `resources` 中的 `temp` 文件夹下的文件。
希望能解决您的问题!如果还有其他疑问,请随时提问。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)