Java file类

33 篇文章 1 订阅

File类是io包中唯一代表磁盘文件本身的对象,可以通过调用File类中的方法,实现创建、删除、重命名文件等。

1. 文件的创建与删除
  可以使用File类创建一个文件对象,三种构造方法的语法格式如下:

new File(String pathname)
new File(String parent, String child)
new File(File f, String child)

pathname是路径名称,parent是父路径字符串,child是子路径字符串,f是父路径对象。如下例:

File file = new File("E:/test.txt");
File file = new File("E:/myword","word.txt");

如果E:/myword目录下没有名称为word的文件,File类对象可通过createNewFile()方法创建一个名称为word.txt的文件;如果存在,可通过delete()方法将其删除。

  1. 获取文件长度
import java.io.File;

public class FileTest {

    public static void main(String[] args) {
        File file = new File("E:/myword", "word.txt");    // 创建文件对象
        if(file.exists()) {    // 判断文件是否存在
            String name = file.getName();    // 获取文件名称
            long length = file.length();    // 获取文件长度
            boolean hidden = file.isHidden();    // 判断文件是否是隐藏文件

            System.out.println("文件名称:" + name);
            System.out.println("文件长度是:" + length);
            System.out.println("是否是隐藏文件:" + hidden);
        } else {
            System.out.println("文件不存在");
        }
    }

}

带缓存的输入/输出流
  缓存是I/O的一种性能优化。缓存流为I/O流增加了内存缓存区。

1. BufferedInputStream类与BufferedOutputStream类
  构造函数如下:

BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int size)
BufferedOutputStream(OutputStream in)
BufferedOutputStream(OutputStream in, int size)

在使用BufferedWriter类的write()方法时,数据并没有立刻被写入到输出流时,而是首先进入缓存区中,如果想立刻将缓冲区中的数据写入输出流中,一定要调用flush()方法。

数据输入/输出流
数据输入/输出流为DataInputStream类与DateOutputStream类,允许应用程序以与机器无关的方式从底层输入流中读取基本Java数据类型。

构造方法如下:

DataInputStream(InputStream in)
DataOutputStream(OutputStream out)

DataOutputStream类提供了以下三种写入字符串的方法:

writeBytes(String s)
writeChars(String s)
writeUTF(String s)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EricFang0001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值