java获取路径的最后目录
时间: 2023-02-10 20:05:49 浏览: 132
你可以使用 java.io.File 类的 getName() 方法来获取路径的最后目录名。例如:
```
String filePath = "/path/to/directory/file.txt";
File file = new File(filePath);
String lastDirectory = file.getName();
System.out.println(lastDirectory); // 输出 "file.txt"
```
如果你想获取包含文件名的完整路径的最后一个目录名,你可以使用 getParent() 方法来获取路径的父目录,然后再使用 getName() 方法获取最后一个目录的名称。例如:
```
String filePath = "/path/to/directory/subdirectory/file.txt";
File file = new File(filePath);
String parentDirectory = file.getParent();
File parent = new File(parentDirectory);
String lastDirectory = parent.getName();
System.out.println(lastDirectory); // 输出 "subdirectory"
```
希望这些信息能帮到你!
相关问题
java multipartfile获取路径
可以使用MultipartFile类的getOriginalFilename()方法获取文件名,然后利用ServletContext类的getRealPath()方法获取上传文件的存储路径,最后拼接出完整的文件路径。具体实现如下:
```
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
String fileName = file.getOriginalFilename();
String filePath = request.getSession().getServletContext().getRealPath("upload/");
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "upload success";
} catch (IOException e) {
e.printStackTrace();
}
return "upload failure";
}
```
java获取相对路径
在 Java 中,你可以使用 `java.nio.file.Paths` 类和 `java.nio.file.Path` 接口来获取相对路径。
这里是一个示例代码:
```
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
// 获取当前工作目录
String currentDirectory = System.getProperty("user.dir");
// 使用 Paths 的静态方法 get() 来获取相对路径
// 相对路径是相对于当前工作目录的
java.nio.file.Path path = Paths.get("relative/path/to/file.txt");
// 使用 toAbsolutePath() 方法将相对路径转换为绝对路径
java.nio.file.Path absolutePath = path.toAbsolutePath();
System.out.println("Absolute path: " + absolutePath);
}
}
```
在这个例子中,我们使用 `System.getProperty("user.dir")` 来获取当前工作目录,然后使用 `Paths.get()` 方法来获取相对路径,最后使用 `toAbsolutePath()` 方法将相对路径转换为绝对路径。
相关推荐
![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)