首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >这个Kotlin FileFilter怎么了?

这个Kotlin FileFilter怎么了?
EN

Stack Overflow用户
提问于 2018-09-29 03:03:20
回答 1查看 4.2K关注 0票数 8

在我的Kotlin应用程序中,我有以下FileFilter:

代码语言:javascript
运行
复制
fileArray = fileDirectory.listFiles { file, filename ->
  file.length() > 0 && filename.matches(fileMatcherRegex)
}

它在文件名匹配器上正确过滤,但不过滤长度为0的文件。我后来遍历了fileArray并记录了每个文件的长度,我可以看到长度为0。

奇怪的是,如果我将file.length() > 0更改为file.length() > 999999999999,它会过滤掉所有文件,因此筛选器的length()元素将被测试。只是没有产生我理解的结果。

我做错了什么?

我的头还在Kotlin lambdas附近,所以我猜我的错误与此有关。

提前感谢

约翰

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-29 05:30:09

listFiles方法需要一个具有两个参数的lambda,该参数基于来自FilenameFilter接口上的该方法的山姆转换

代码语言:javascript
运行
复制
/**
 * Tests if a specified file should be included in a file list.
 *
 * @param   dir    the directory in which the file was found.
 * @param   name   the name of the file.
 * @return  <code>true</code> if and only if the name should be
 * included in the file list; <code>false</code> otherwise.
 */
boolean accept(File dir, String name);

第一个参数是包含文件的目录,而不是文件本身。只有第二个参数表示目录中的文件。所以您的file.length()正在检查fileDirectory.length()而不是文件的长度。

实际上,将原始代码读为:

代码语言:javascript
运行
复制
val fileArray = fileDirectory.listFiles { directory, filename ->
  directory.length() > 0 && filename.matches(fileMatcherRegex)
}

现在你可以看到这是不正确的逻辑。

如果对lambda使用单个参数,则根据来自山姆转换接口的FileFilter指定一个参数,即:

代码语言:javascript
运行
复制
/**
 * Tests whether or not the specified abstract pathname should be
 * included in a pathname list.
 *
 * @param  pathname  The abstract pathname to be tested
 * @return  <code>true</code> if and only if <code>pathname</code>
 *          should be included
 */
boolean accept(File pathname);

这是正确的问题,你问的是关于文件的问题,而不是包含的目录。然后,您的代码将是:

代码语言:javascript
运行
复制
val fileArray = fileDirectory.listFiles { file ->
  file.length() > 0 && file.name.matches(fileMatcherRegex) 
}
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52564713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档