文件对象和方法
创建文件
File file = new File("D://test");
文件方法
file.canWriter();
file.canRead();
file.exists();
file.isFile();
file.isDirectory();
file.createNewFile(); //创建新文件并且返回创建结果,如果文件对象指向的路径存在,则返回false
file.delete(); //只能删除空文件夹或文件
file.length();
file.getPath(); //获取相对路径
file.getAbsolutePath(); //获取绝对路径
file.listFiles(); //获取文件的所有直接子文件或直接子目录
操作文件的两个工具类Paths和File
文件流
基本的文件流的读是i.read(storage)
对象流和缓存流的读是storage = i.read();
字节文件流
字节文件流的写,可以写一个byte,也可以写一个byte数组,还可以写byte数组时指定开始的下标和写入的长度
写入时如果直接创建文件流对象,写入的方式为覆盖
想要写入时是追加方式,需要手动设置
读取方式类似,读取时会有指针移动,在读取完当前内容后指针会自动移动到新的内容
is.read('s');
//获取文件流对象
OutputStream os = new FileOutputStream(file);
//设置为追加写入方式
OutputStream os = new FileOutputStream(file,true);
//写入单个字节
os.write('a');
//写时确定开始下标和长度
OutputStream os = new FileOutputStream(file);
byte[] cs = {'a','b','c','d','e'};
os.write(cs,2,2);
//直接写入整个数组
os.write(cs);
//将缓存中的数据写入内存
os.flush();
//关闭文件流
os.close();
对象文件流
对象文件流基于字节流,并且能够存储进入文件的对象只能是实现了serializable接口的类的对象
并且存入时文件中不能有除了对象数据之外的其他数据
Test t1 = new Test();
Test t2 = new Test();
t1.i = 1;
t2.i = 2;
OutputStream os = new FileOutputStream(file,true);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(t1);
oos.writeObject(t2);
oos.flush();
InputStream is = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(is);
Test t3 = (Test)ois.readObject();
Test t4 = (Test)ois.readObject();
System.out.println(t3.i);
System.out.println(t4.i);
oos.close();
ois.close();
os.close();
is.close();