Java 判断路径是否存在
时间: 2023-10-31 21:06:42 浏览: 38
可以使用 Java 的 File 类的 exists() 方法来判断路径是否存在。
示例代码:
```java
import java.io.File;
public class PathExist {
public static void main(String[] args) {
String path = "/path/to/file";
File file = new File(path);
if (file.exists()) {
System.out.println("路径存在");
} else {
System.out.println("路径不存在");
}
}
}
```
在上述代码中,我们首先定义了一个路径字符串,然后创建一个 File 对象,将路径字符串传递给构造函数。接着,我们调用 exists() 方法来判断路径是否存在,如果存在,则输出“路径存在”,否则输出“路径不存在”。
相关问题
java判断路径是否存在,不存在则创建
在Java中,您可以使用File类来判断路径是否存在,并在路径不存在时创建路径。以下是示例代码:
```java
File file = new File("path/to/directory");
// 判断路径是否存在,如果不存在则创建
if (!file.exists() || !file.isDirectory()) {
boolean success = file.mkdirs();
if (success) {
System.out.println("路径创建成功!");
} else {
System.out.println("路径创建失败!");
}
} else {
System.out.println("路径已经存在!");
}
```
在上面的代码中,我们首先创建一个File对象,表示要判断的路径,然后使用`exists()`方法判断该路径是否存在。如果路径不存在或者不是一个目录,就调用`mkdirs()`方法来创建路径。`mkdirs()`方法会创建路径中所有不存在的目录,并返回一个布尔值,表示创建是否成功。最后,根据`mkdirs()`方法的返回值输出结果。
需要注意的是,如果您要创建的路径包含多级目录,应该使用`mkdirs()`方法。如果只是创建单级目录,可以使用`mkdir()`方法。
Java jsonpath判断路径是否存在
你可以使用com.jayway.jsonpath.JsonPath类的read()方法来读取json数据并判断路径是否存在。以下是一个示例代码:
```java
import com.jayway.jsonpath.JsonPath;
String json = "{\"person\":{\"name\":\"John\",\"age\":30}}";
boolean isNamePresent = JsonPath.read(json, "$.person.name") != null;
boolean isAddressPresent = JsonPath.read(json, "$.person.address") != null;
System.out.println("isNamePresent: " + isNamePresent);
System.out.println("isAddressPresent: " + isAddressPresent);
```
在上面的代码中,我们首先定义了一个包含“person”对象的json字符串。然后我们使用JsonPath类的read()方法来读取json数据并判断路径是否存在。 "$.person.name"表示我们要查找json中“person”对象的“name”属性是否存在。如果存在,则返回true,否则返回false。
同样,我们还可以使用相同的方式来判断其他路径是否存在。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)