使用 application.yml 配置文件获取绝对路径进行文件操作

在 Spring Boot 应用中,可以使用 application.yml 配置文件配置绝对路径,方便在代码中进行文件操作。

1. 配置绝对路径

application.yml 中,你可以像下面这样配置绝对路径:

file:
  path: '/home/user/files/'

2. 代码中获取路径并进行文件操作

通过 @Value 注解注入配置,然后使用 Java IO 或 NIO API 进行文件操作,例如:

@Service
public class FileService {

    @Value('${file.path}')
    private String filePath;

    public void writeFile(String fileName, String content) throws IOException {
        Path path = Paths.get(filePath, fileName);
        Files.write(path, content.getBytes());
    }

    public String readFile(String fileName) throws IOException {
        Path path = Paths.get(filePath, fileName);
        return new String(Files.readAllBytes(path));
    }
}

注意事项

  • 确保配置的路径存在且有足够的权限。
  • 在生产环境中,建议使用相对路径或环境变量来配置文件路径,提高代码的可移植性。
Java 使用 application.yml 配置文件获取绝对路径进行文件操作

原文地址: https://www.cveoy.top/t/topic/n6sC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录