文件file类的使用和异常

来源:互联网 发布:微信拼图游戏源码 编辑:程序博客网 时间:2024/05/16 06:03

文件file类:

常用构造函数File(String pathname)

File   file=new File("路径");

若此路径表示一个文件时,并且在实际存储空间不存在时

可以和file.createNewFile()搭配使用会创建此文件,

file.delete()可删除;

file.exists()判断指定该路径是否存在,返回类型布尔类型;

file.getAbsolutepath返回此路径名的绝对路径名字符串;

file.getParent()返回次路径父目录的路径名字符串,若没有则返回null;

file.isFile()测试是否是一个标准文件;

file.list()

file.listFiles();


字节流:输入流FileInputStream

常用构造函数FileInputStream(String name)

FileInputStream fis=new FileInpputStream("路径名");

fis.close关闭通道;

fis.read()读取一个字节;

fis.read(byte[] b)具体使用如下:

byte[] bytes=new byte[14];
int value=fis.read(bytes);
while(value!=-1){
for(int i=0;i<value;i++){
System.out.println((char)bytes[i]);
}
count++;
System.out.println("0000000000"+count);
value=fis.read(bytes);
}

fis.read(byte[] b,int off,int len);

输出流FileOuputStream

常用构造函数FileOutputStream("指定名称文件路径名")

常用构造函数FileOutputStream("指定名称文件路径名",boolean append)后一个参数是是否在一个文件在后面继续添加还是覆盖

FileOuputStream  fos=new FileOuputStream("文件路径名");

文件名可以不存在,,,但路径必须存在

fos.close关闭操作;

fos.write(byte[] b);

fos.write(byte[] b,int off,int len);

fos.write(int b)此方法是将指定字节写入此文件输出流;

FileOutputStream fos=new FileOutputStream("输出流测试.txt",true);
byte[] bytes={97,98,99,100,101,102};
fos.write(bytes,2,3);


文件复制:

FileOutputStream fos=new FileOutputStream("读出.txt");

FileInputStream fis=new FileInputStream(files);

byte[] bytes=new byte[255];
fis.read(bytes);
fos.write(bytes);

fis.close();

fos.close();


异常:


0 0