---
title: "根据文件路径分别获取文件名和文件目录"
author: "413899327"
date: "2010-11-24T20:50:03Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-11-24T20:50:43Z"
id: 821774
url: "https://rogerfederer.iteye.com/blog/821774"
---

```java

	 String path = "C:\\xxx\\a.txt";
		 //获取文件名之前的目录
		 String directoryStr = path.substring(0, path.lastIndexOf(File.separator));
		 
		 System.out.println("File.separator = "+File.separator);
		 System.out.println("path.length() = "+path.length()+"\npath.lastIndexOf(File.separator) = "+path.lastIndexOf(File.separator));
		 System.out.println("directoryStr = "+directoryStr);
		 
		 //获取文件名
		 String directoryStr2 = path.substring(path.lastIndexOf(File.separator)+1);
		 System.out.println(directoryStr2);
```
	

结果：


```java
File.separator = \
path.length() = 12
path.lastIndexOf(File.separator) = 6
directoryStr = C:\xxx
a.txt
```