Java 文件名过滤器
我需要获取目录中具有特定扩展名(例如 .txt)的所有文件。我应该能够列出所有具有“.txt”和“.TXT”扩展名的文件(即,它应该不区分大小写)。我为此编写了以下课程。为了实现这一目标,我应该在下面的课程中做出什么改变?
class OnlyExt implements FilenameFilter {
String ext;
public OnlyExt(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
}
好吧,我在 accept()
中尝试了 name.toLowerCase().endsWith(ext);
,但没有成功。
提前致谢。
I have a requirement to get all of the files in a directory that have a specific extension(say, .txt). I should be able to list all of the files that have '.txt' and '.TXT' extension (i.e., it should be case insensitive). I've written the following class for this. What change should I make in the following class to achieve this?
class OnlyExt implements FilenameFilter {
String ext;
public OnlyExt(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
}
Well, I tried name.toLowerCase().endsWith(ext);
in the accept()
, but that didn't work.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您还需要将扩展名小写。
另外,检查构造函数以查看是否已经存在前导“.”可能是个好主意。如果是这样,则不要在前面添加另一个。
You need to lowercase the extension, too.
Also, it might be a good idea to check in the constructor to see if there's already a leading "." and not prepend another if so.