2021-06-29

File类

在 Java 中,File 类是 java.io 包中唯一代表磁盘文件本身的对象。File 类定义了一些与平台无关的方法来操作文件,File类主要用来获取或处理与磁盘文件相关的信息,像文件名、 文件路径、访问权限和修改日期等,还可以浏览子目录层次结构。
  File 类表示处理文件和文件系统的相关信息。也就是说,File 类不具有从文件读取信息和向文件写入信息的功能,它仅描述文件本身的属性。
  File类可以分为两种,一种为文件夹,即是Directory,另一类是普通文件,File。

普通文件的创建
File file = new File("D:\\XXX.txt")//不管存在与否,都可以使用,这句话的作用为指定当前文件
if(file.exist()){//如果文件存在,则不创建,不存在,则创建该文件
} else file.createNewFile();
文件夹的创建
File file = new File("D:\\XXX")//不管存在与否,都可以使用,这句话的作用为指定当前文件夹
if(file.exist()){//如果文件存在,则不创建,不存在,则创建该文件
} else file.mkdirs();
//mkdir只是创建抽象路径指定为目录,但并不知道父类目录是否存在,而mkdirs是创建该抽象目录和父类路径

File类的其他方法

查询文件是否存在:

   File.exist();       
 //返回的值是布尔值,0代表不存在,1代表存在。

获取文件的大小:

  File.length(); 
 //返回的值为Long类型,以字节为单位,英文占一个字节,汉字占三个字节。

删除文件:

File.Delete();
//删除文件或文件夹

获取文件或目录名称:

File. getname();
//获取文件夹或文件名字

获取文件或目录路径:

File. getAbsolutePath();
//获取文件夹或文件绝对路径
File.getPath();
//获取文件夹或文件路径

递归调用自己,

利用高级For循环,
for(File file:File[ ])
for(数据类型 变量名:数组或集合)

IO流

IO流分为输入和输出流两种,在此两类中,祖宗类为InputStream和OutputStream
在输入流中,子类有FileInputStream和BufferedInputStream。
在输出流中,子类有FileOutputStream和BufferedOutputStream。

FileInputStream

FileInputStream fis= new FileInputStream("xxx");
FileInputStream fis= new FileInputStream(new File);

两种构造方法,一种传入路径,一种指定文件。

读取方法

fis.read();
//一个一个字节的读取,速度很慢,返回Int值
if(fis.read()=-1){//如果读取值为-1,说明此字符为null
}
fis.close();//关闭数据流

FileOutputStream

FileOutputStream fos= new FileOutputStream("xxx");
//传入Path

写入方法

String data = "hello"
byte[] b = data.getBytes();
fos.write(b);
//如果没有文件,自动创建文件。

FileIO实例

FileInputStream fis = new FileInputStream("C:\\...");
FileOutputStrem fos = new FileOutputStream("E:\\...");
int ch = 0;
while((ch=fis.read())!=-1)
{fos.write(ch);
//把C盘的。。。文件写入E盘
}

由于File的io流每次只能读取或者写入一个字节,因此,我们会经常用到BufferedInputStream或BufferedOutputStream

BuffedInputStream

BufferedInputStream又称字节缓存输入流,相比FileInputStream效率更好,一次写入多个字节。

BufferedInputStream bis = new BufferedInputStream(InputStream is);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\..."));
//若要使用效率高的,应当先创建效率低的。

byte[] car = new byte[1024];//一次读取1kb
int len = 0;
while((len=bis.read(car))=-1){
System.out.printin(car)
}//len=-1说明读完了
bis.close();

BufferedOutputStream

BufferedOutputStream bos= new BufferedOutputStream(new FileOutputStream("D:\\"));
String data = "..."
byte[] b = new byte[1024];
b = data.getBytes();
int len = 0;
bos.write(b,0,len);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值