File I/O

本文详细介绍了Java中File类的方法及构造函数,展示了如何使用这些方法进行文件和目录的操作。此外,还介绍了InputStream、OutputStream、Reader和Writer类的常用方法,帮助开发者更好地理解和使用Java的IO操作。

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

File类的常用方法


boolean exists() 判断文件或目录是否存在

boolean ifFile() 判断是否是文件

boolean isDirectory() 判断是否是目录

String getPath () 返回此对象表示的文件的相对路径名

String getAbsolutePath () 返回此对象表示的文件的绝对路径名

String getName () 返回此对象表示的文件或目录的名称

boolean delete () 删除此对象指定的文件或目录

boolean createNewFile ()创建名称的空文件,不创建文件夹

long length()返回文件的长度,单位为字节,若文件不存在,则返回 OL

                                                                         File构造函数

File 有参构造有三种分别:

File (String pathname) 通过指定的路径/来创建File对象

File (String parent,String child) 通过一个目录和一个子文件/来创建File对象

File (File parent,String child) 通过一个File对象和一个子文件/来创建File对象


File (String pathname) 实例:

File parent = new File("E:\\Test\\aa");
//      exists 判断文件或目录是否存在;存在为true
    if(!parent.exists()){
//          mkdirs 创建多级目录
        parent.mkdirs();
    }

File (String parent,String child) 实例:

//      File(String parent, String child) 
    File child = new File("E:\\Test\\A","child");
    if(!child.exists()){
        child.mkdirs();
    }


File (File parent,String child) 实例:

        File parent = new File("E:\\Test\\aaa");
    if(!parent.exists()){
        parent.mkdirs();
    }

//      File(File parent, String child)
// 和上面的类似,通过 parent和child 创建一个文件或者目录
    File child = new File(parent,"child");
    if(!child.exists()){
        child.mkdirs();
    }


InputStream类  的常用方法

int available()返回输入流读取的估计字节数

int read()读取一个字节数据

int read(byte[] b) 将数据读取到字节数组中

int read (byte[] b, int off, int len) 从输入流中读取最多Len长度的字节,保存到字节数组b中,保存的位置从off开始

void close() 关闭输入流


OutputStream 类的常用方法

void write(int c) 写入一个字节数据

void write(byte[] buf) 写入数组buf的所有字节

void write(byte[] buf,int off,int len)将字节数组中从off位置开始,长度为len的字节数据输出到输出流中

void close()关闭输出流


Reader 类常用方法

int read()从输入流中读取单个字节

int read(byte[] c)从输入流中读取c.length长度的字符,保存到字符数组c中,返回实际读取的字符数

int read(byte[] c,int off,int len)从输入流中读取最多len的长度字符,保存到字符数组c中,保存的位置从off位置开始,返回实际读取的字符长度

void close()关闭流

Writer 类的常用方法

write(String filename)将str字符串里包含字符输出到指定的输出流中

write(String str,int off,int len)将str字符串里从off位置开始的长度为len的字符输出到输出流中

void close()关闭输出流类

void flush()刷新输出流

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值