File

来源:互联网 发布:mac钥匙串在哪 编辑:程序博客网 时间:2024/06/05 20:17

File类:电脑磁盘操作类,文件和目录路径名的抽象表示形式。
File(String pathname):通过制定路径字符串创建file
构造方法
1.File file = new File(“E:/File/testFile1.txt”);
2.File file = new File(“E:\Fil\testFile1.txt”);
3.String destDirectory=”c:/picture”;
//获取源文件夹中所有文件
File files[]=file.listFiles();
File destFile=new File(destDirectory,file2.getName());//根据父路径名和其下文件名创建
普通方法
1.文件
createNewFile():当文件不存在时创建文件 有异常
Length():返回文件长度
2**.文件夹**
Mkdir():创建指定目录的文件
Mkdirs():创建文件,父目录不存在时也会创建。
listFiles():返回目录下的文件数目
List(FilenameFilter filter):返回满足特定过滤条件的文件数目
3.共有
delete()
getName()
getPath()
getParent():返回父路径字符串,没有则返回null
getParentFile():返回父路径FIIle,没有null
getAbsoFile():绝对路径
注意:getXXX方法中带file的返回的是File 不带的返回的是String
exists()
isFile():是否是一个标准文件
isDirectory():是否是目录
renameTo():
File newFile=new File(“c:/java/code/b.txt”);
file.renameTo(newFile);
//重命名之后的file对象 不能使用file对象进行调用
lastModified()
canRead():
canWrite()
SetReadOnly() 文件后缀名:fileName.endsWith(“dll”)
InputStream :FileInputStream 从文件系统中的某个文件中获得输入字节
read(),read(byte[] b),read(byte[] b,int off,int len)3个方法的区别
1.Read:从输入流中读取一个字节
2.read(byte[] b)::从输入流中最多读取b.length个字节。
B:存储读取数据的缓冲区
当到达文件尾部没有更数据时返回-1
3.read(byte[] b,int off,int len):从此输入流中最多将len个字节数据读入byte数组中。Off:开始读入位置 Len——>b
OutputStream:FileOutputStream
1.write(int):每次写一个字节
2.write(byte b[]):表示每次写b数组中的内容到文件
3.write(byte b[],int offset,int len):将数组b中len长度的字节写入,从offset处开始
文件内容读写:
步骤:
1.文件定位 File
2.搭建桥梁InputStream/InputStream
3.读写字节文件
4.关闭流close
1,2步骤可以直接合并为一步骤
详细:
InputStream is = new FileInputStream(“c:/java/code/b.txt”);
byte b[] = new byte[7];// 缓存
int len=0; //实际读取长度
while((len=is.read(b))!=-1)//每次按照缓存实际长度满读,最后一次可能读不满。
{
System.out.print(new String(b,0,len)); //每次要转换的b长度为len(最后一次可能小于前面次数不同。)
}

if (is != null) {
try {
is.close();
注意下面创建流的方式:
//创建流的方式
FileInputStream fis = new FileInputStream(file.getPath() + File.separator + fileName);

0 0
原创粉丝点击