Java 日看一类(18)之IO包中的FileNameFilter接口类和FileNotFoundException异常类

本文介绍了Java中FileNameFilter接口的功能及使用场景,该接口用于过滤文件名。同时详细解释了FileNotFoundException异常,包括其作用、构造方法及应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FileNameFilter接口未引入任何包



该类类头注释如下:

/**
 * Instances of classes that implement this interface are used to
 * filter filenames. These instances are used to filter directory
 * listings in the <code>list</code> method of class
 * <code>File</code>, and by the Abstract Window Toolkit's file
 * dialog component.
 *
 * @author  Arthur van Hoff
 * @author  Jonathan Payne
 * @see     java.awt.FileDialog#setFilenameFilter(java.io.FilenameFilter)
 * @see     java.io.File
 * @see     java.io.File#list(java.io.FilenameFilter)
 * @since   JDK1.0
 */

大意如下:

实现该接口的类可对文件名进行过滤

Abstract Window Toolkit 的文件对话框组件使用这些实例过滤File类的list方法中的目录清单




仅含有一个成员方法:

检测特定的文件是否存在于该文件列表中(dir中为文件所在目录,string为文件名

boolean accept(File dir, String name);



该类十分简单,不再过多叙述



FileNotFoundException异常类继承自IOException


类头注释如下:

/**
 * Signals that an attempt to open the file denoted by a specified pathname
 * has failed.
 *
 * <p> This exception will be thrown by the {@link FileInputStream}, {@link
 * FileOutputStream}, and {@link RandomAccessFile} constructors when a file
 * with the specified pathname does not exist.  It will also be thrown by these
 * constructors if the file does exist but for some reason is inaccessible, for
 * example when an attempt is made to open a read-only file for writing.
 *
 * @author  unascribed
 * @since   JDK1.0
 */

大意如下:

该异常类标志着打开指定路径文件失败

当需要打开的文件不存在时这个异常将会被FileInputStreamFileOutputStream,RandomAccessFile的构造函数抛出

当需要打开的文件由于某些特定原因无法打开时(如尝试去用写入方式打开只读文件)也会被抛出



该类含有一个成员变量:

序列化ID:

private static final long serialVersionUID = -897856973823710492L;


含有三个方法:

默认构造方法:直接调用父类构造方法

public FileNotFoundException() {
    super();
}

构造方法:(也对应父类构造方法,把具体错误信息的字符串传递给父类

public FileNotFoundException(String s) {
    super(s);
}

构造方法:仅能被native IO方法调用(私有),传递出错的路径和错误原因

private FileNotFoundException(String path, String reason) {
    super(path + ((reason == null)//检测错误原因是否为空
                  ? ""
                  : " (" + reason + ")"));
}



这个类也十分简单,编写时遇到该异常知道错误原因即可


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值