file.getName().contains("s");
时间: 2024-06-08 13:09:01 浏览: 7
这行代码的作用是判断`file`对象所代表的文件名是否包含字母`s`,如果包含则返回`true`,否则返回`false`。`getName()`是Java中的一个`File`类的方法,用于获取文件名。`contains()`是Java中String类的方法,用于判断字符串中是否包含指定的字符或字符串。
相关问题
if (dir!=null&&dir.isDirectory()){ File[] files = dir.listFiles(); System.out.println(Arrays.toString(files)); for (File file : files) { if (file.isFile()&& file.getName().contains(s2)){ System.out.println("找到了,路径是"+file.getAbsolutePath()); } if (file!=null&&file.isDirectory()){ search(file,s2); } } }else{ System.out.println("您输入的不是文件夹"); }为什么空指针
可能会在两个地方产生空指针异常:
1. 当 `dir` 为 `null` 时,调用 `dir.isDirectory()` 会抛出空指针异常。
2. 在 `for` 循环中,如果 `files` 中存在为 `null` 的元素,调用 `file.isFile()` 或 `file.getName()` 会抛出空指针异常。
为了避免这些异常,应该在使用这些变量或方法之前,先进行非空判断。例如,可以在调用 `dir.isDirectory()` 之前,先判断 `dir` 是否为 `null`,如果是,则不执行后续代码。在 `for` 循环中,可以使用 `if` 判断 `file` 是否为 `null`,如果是,则跳过本次循环。
public static void serachFile(File dir,String s){ if (dir==null||dir.isFile()) { return ; } File[] files = dir.listFiles(); for (File file : files) { if (file!=null&&file.isDirectory()){ serachFile(file,s); }else { if (file.getName().contains(s)){ System.out.println("找到了,路径在"+file.getAbsolutePath()); System.out.println("找到了,路径在"+file.getPath()); } } } }
这段代码是用来搜索包含特定字符串的文件的,它使用了递归的方式来遍历指定文件夹下的所有文件和子文件夹。参数`dir`表示要搜索的文件夹,参数`s`表示要搜索的字符串。首先判断`dir`是否为空或者是否为文件,如果是则直接返回。然后获取`dir`下的所有文件和文件夹,遍历每一个文件或文件夹,如果是文件夹,则递归调用`serachFile`方法,如果是文件,则判断文件名是否包含要搜索的字符串`s`,如果包含,则输出文件的绝对路径和相对路径。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)