行业知识
Java获取resources下文件路径
2026-12-05 17:19:00
来源:互联网转载
方法一:使用ClassLoader.getResource()方法
String filePath = "path/to/file.txt";URL resourceUrl = getClass().getClassLoader().getResource(filePath);String resourcePath = resourceUrl.getPath();
方法二:使用ClassLoader.getResourceAsStream()方法
String filePath = "path/to/file.txt";InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filePath);
方法三:使用Class.getResource()方法
String filePath = "path/to/file.txt";URL resourceUrl = getClass().getResource(filePath);String resourcePath = resourceUrl.getPath();
方法四:使用Class.getResourceAsStream()方法
String filePath = "path/to/file.txt";InputStream inputStream = getClass().getResourceAsStream(filePath);
问题记录
获取resources目录下某index.php/tags-522.html" >文件路径并返回
()public String getResourcesPath(String filePath) { String resourcePath=null; try { Resource resource = new ClassPathResource(filePath); Path path = resource.getFile().toPath(); resourcePath=path.toString(); } catch (IOException e) { throw new RuntimeException(e); } return resourcePath; } 此处也能获取到文件路径 仅限本地 当jar包时 是无法获取到该文件具体的路径的 我的解决方案如下:
public String getResourcesPath(String filePath) { String resourcePath=null; File file = new File(filePath); try { Resource resource = new ClassPathResource(filePath); InputStream inputStream = resource.getInputStream(); FileUtils.copyInputStreamToFile(inputStream, file); resourcePath=file.getAbsolutePath(); } catch (IOException e) { throw new RuntimeException(e); } return resourcePath; } 从流中获取
()上一篇:电脑fonts字体教程
下一篇:游戏服务器性能怎么描述?