发现把代码打成jar包之后,放在linux环境上运行,是无法通过路径去读取文件的。
一个解决方案就是把相对路径的资源读出流,生成一个文件放在linux环境上(多服务器的情况,不需要自己手动放文件上去),这样就能读文件路径了。
文件在项目里面放的位置:
代码如下:
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.InputStream;
/**
* @Author ckl
* @Date 2022-09-24 16:41
*/
@Slf4j
public class FileUtil {
/**
* linux下运行jar,通过路径获取文件的绝对路径
* @param path 传相对路径 比如 cert/alipay/xxx.crt
* @return 返回的路径就是放在linux服务器上的文件路径
*/
public static String getFileAbsolutePath(String path){
try {
// 创建临时文件,获取jar里面的配置文件
File file = new File("/home/file/" + path);
if(file.exists()){
return file.getAbsolutePath();
}
InputStream inputStream = null;
try {
ClassPathResource resource = new ClassPathResource(path);
inputStream = resource.getInputStream();
FileUtils.copyInputStreamToFile(inputStream, file);
return file.getAbsolutePath();
} finally {
IOUtils.closeQuietly(inputStream);
}
} catch (Exception e) {
log.error("FileUtil getFilePath Fail cause by:",e);
}
return null;
}
/**
* 读网络上的文件地址,上传到本地
* @param url 如:https://www.baidu.com/xxx.crt 文件外网地址
* @return
*/
public static String uploadToLocalByUrl(String url){
try {
// 文件名
String fileName = url.substring(url.lastIndexOf("/")+1);
File file = new File("/home/file/" + fileName);
if(file.exists()){
return file.getAbsolutePath();
}
InputStream inputStream = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class);
inputStream = new ByteArrayInputStream(Objects.requireNonNull(response.getBody()));
FileUtils.copyInputStreamToFile(inputStream, file);
return file.getAbsolutePath();
} finally {
IOUtils.closeQuietly(inputStream);
}
} catch (Exception e) {
log.error("PayFileUtil uploadToLocalByUrl Fail cause by:",e);
}
return null;
}
}