一.IO流简介
1.定义:对文件的内容进行读和写的操作。
2.路径:
相对路径:相对当前文件所在的路径
据对路径:带有盘符的路径 D:\io\Hello.txt
二.IO流的分类
1、按照流向分:输入流 输出流
2、按照单位分:字节流 字符流
3、拉照角色分:节点流 处理流
三.IO流的常用方法
1、文件类的创建写法:
2.io流的普通方法
public String getAbsolutePath():获取绝对路径
public String getPath() :获取路径
public String getName() :获取名称
public String getParent():获取上层文件目录路径。若无,返回null
public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
public long lastModified() :获取最后一次的修改时间,毫秒值
public boolean isDirectory():判断是否是文件目录
public boolean isFile() :判断是否是文件
public boolean exists() :判断是否存在
public boolean canRead() :判断是否可读
public boolean canWrite() :判断是否可写
public boolean isHidden() :判断是否隐藏
如下的两个方法适用于文件目录:
public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组
public boolean renameTo(File dest):把文件重命名为指定的文件路径
比如:file1.renameTo(file2)为例:
要想保证返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在。
四.流的基本结构
1.写法步骤
(1)先创建文件类
(2)创建流
(3)写操作
(4)关流:close();
2.例子1:读取操作:FileReader来读取一个文件,如果文件到达最后一个位置(即-1),就停止读取操作。
3.例子2:写入操作:向文件 hello2.txt中写内容。
4.使用字符流文件的复制
public class TestCopy { public static void main(String[] args) { File f1=new File("hello2.txt"); File f2=new File("hello3.txt"); FileReader fr=null; FileWriter fw=null; try { fr=new FileReader(f1); fw=new FileWriter(f2); char [] cbuf=new char[30]; int len; while((len=fr.read(cbuf))!=-1){ fw.write(cbuf,0,len); } } catch (Exception e) { throw new RuntimeException(e); }finally { if(fw!=null){ try { fw.close(); } catch (IOException e) { throw new RuntimeException(e); } } if(fr!=null){ try { fr.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } }
5.使用字节流进行文件的复制的操作
6.节点流和缓冲流的对比,可见缓冲流更为高效。