Java在applicationyml配置文件配置绝对路径在文件中调用
在application.yml配置文件中配置绝对路径,可以像下面这样:
file:
path: /home/user/files/
然后在代码中通过注入配置的方式获取路径,并使用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));
}
}
这样就可以在代码中使用绝对路径进行文件操作了。注意,需要确保配置的路径存在且有足够的权限
原文地址: https://www.cveoy.top/t/topic/fd5m 著作权归作者所有。请勿转载和采集!