String resourcePath = getClass().getClassLoader().getResource("").getPath();获得的路径是E:\%e5%8a%a8%e5%8a%9b%e8%8a%82%e7%82%b9\Java\xml-annotation-orm\out\production\xml-orm-mysql-reflection\,只想要xml-orm-mysql-reflection\该怎么做
时间: 2023-07-21 18:59:53 浏览: 76
如果您只想要路径中的 "xml-orm-mysql-reflection\" 部分,您可以使用以下代码来获取它:
```java
String resourcePath = getClass().getClassLoader().getResource("").getPath();
String desiredPath = resourcePath.substring(resourcePath.lastIndexOf("xml-orm-mysql-reflection"));
```
这将从 `resourcePath` 字符串中获取最后出现的 "xml-orm-mysql-reflection" 部分及其后面的内容。请注意,这假设 "xml-orm-mysql-reflection\" 是路径中的最后一个目录,并且没有文件名或其他内容跟在它的后面。
相关问题
下面这两段代码的区别在哪?业务中如何区分使用?String path1 = new ClassPathResource("").getAbsolutePath(); String path2 = getClass().getClassLoader().getResource("").getPath();
这两段代码的功能都是获取当前项目的根路径。
区别在于:
- 第一种方式使用Spring提供的ClassPathResource类,需要依赖Spring框架,而第二种方式则是使用Java标准库中的ClassLoader类,不需要依赖任何框架。
- 第一种方式返回的是项目的classes目录的绝对路径,而第二种方式返回的是项目的根目录的绝对路径。
业务中如何选择使用呢?
- 如果你的项目中使用了Spring框架,那么可以使用第一种方式。
- 如果你的项目中没有使用Spring框架,或者不想依赖任何框架,那么可以使用第二种方式。
注意:在使用第二种方式时,需要注意路径中可能会包含空格或其他特殊字符,需要进行URL解码。可以使用如下方式进行解码:
```
String path2 = URLDecoder.decode(getClass().getClassLoader().getResource("").getPath(), "UTF-8");
```
String uploadPath = Objects.requireNonNull(this.getClass().getClassLoader().getResource("./moulds/tempFile")).getPath();想将这个中的文件以输出流形式打开,结果打不开office
这个问题可能是因为你使用的是相对路径,而不是绝对路径,导致程序无法正确找到文件。可以尝试使用绝对路径来打开文件,例如:
```
String absolutePath = new File(uploadPath).getAbsolutePath();
```
然后再使用绝对路径来打开文件,例如:
```
InputStream inputStream = new FileInputStream(absolutePath);
```
或者你也可以使用Java 7的NIO库来打开文件,例如:
```
Path path = Paths.get(absolutePath);
InputStream inputStream = Files.newInputStream(path);
```
此外,如果你打开的是Office文档,建议使用对应的Office API来处理,而不是直接以输入流的形式打开文件。例如,对于Word文档,你可以使用Apache POI库来读取和操作文档。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)