这些无法获取springboot项目下的resources路径下的资源文件,
因为资源文件再本地是D://**/target/class/
而linux服务器是**/BOOT-INF/路径下,
会导致程序找不到文件异常
本地jar文件下resources路径
通过绝对路径获取项目中文件的位置,只是本地绝对路径,不能用于服务器获取
String rootPath = System.getProperty("user.dir");
通过new File("")获取当前的绝对路径,只是本地绝对路径,不能用于服务器获取。
# 此处借鉴它人代码
//参数为空
File directory = new File("");
//规范路径:getCanonicalPath() 方法返回绝对路径,会把 ..\ 、.\ 这样的符号解析掉
String rootCanonicalPath = directory.getCanonicalPath();
//绝对路径:getAbsolutePath() 方法返回文件的绝对路径,如果构造的时候是全路径就直接返回全路径,如果构造时是相对路径,就返回当前目录的路径 + 构造 File 对象时的路径
String rootAbsolutePath =directory.getAbsolutePath();
System.out.println(rootCanonicalPath);
System.out.println(rootAbsolutePath);
通过类加载器获取resource下的路径
URL resource1 = Command.class.getClassLoader().getResource("exe/futureelectronics.exe");
System.out.println(resource1);
URL resource2 = this.getClass().getClassLoader().getResource("exe/futureelectronics.exe");
System.out.println(resource2);
通过类加载器获取resource下的路径,并过滤中文路径
//注意getResource("")里面是空字符串
String path = this.getClass().getClassLoader().getResource(fileName).getPath();
System.out.println(path);
//如果路径中带有中文会被URLEncoder,因此这里需要解码
String filePath = URLDecoder.decode(path, "UTF-8");
System.out.println(filePath);
以下再springboot容器中可以获取resources下文件路径
通过spring的Resource接口下面的实现类(子类)获取路径(推荐)
Resource源码
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.core.io;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import org.springframework.lang.Nullable;
public interface Resource extends InputStreamSource {
boolean exists();
default boolean isReadable() {
return this.exists();
}
default boolean isOpen() {
return false;
}
default boolean isFile() {
return false;
}
URL getURL() throws IOException;
URI getURI() throws IOException;
File getFile() throws IOException;
default ReadableByteChannel readableChannel() throws IOException {
return Channels.newChannel(this.getInputStream());
}
long contentLength() throws IOException;
long lastModified() throws IOException;
Resource createRelative(String var1) throws IOException;
@Nullable
String getFilename();
String getDescription();
}
Resource的实现类
ResourceLoader的实现类
XmlWebApplicationContext来获取resources下路的路径
Resource resource = new XmlWebApplicationContext().getResource("classpath:exe/futureelectronics.exe");
String path = new ClassPathResource(ExeConstant.EXE_DEFAULT_PATH).getPath();
System.out.println(path);
# 获取资源定位符
String uri = new ClassPathResource(ExeConstant.EXE_DEFAULT_PATH)..getURL();
System.out.println(uri);
ClassPathResource获取流
new ClassPathResource(ExeConstant.SUNLOCAL_XLSX_PATH).getInputStream()
直接使用getResourceAsStream方法获取流(推荐)
InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName);