视频链接:https://www.bilibili.com/video/BV1Rx411876f?p=1
视频范围P743 - P756
目录描述
1.File类的理解和常用方法
- File类和四大家族没有关系,所以File类不能完成文件的读和写
- File对象代表文件和目录路径名的抽象表示形式
- 需要掌握File类中常用的方法
代码实例一:
exists(),createNewFile(),mkdir(),mkdirs(),getParent(),getParentFile(),getAbsolutePath()
package IO;
import java.io.File;
public class FileTest01 {
public static void main(String[] args) throws Exception{
//创建一个File对象
File f1 = new File("D:\\file");
//判断是否存在!
System.out.println(f1.exists());//输出为:false
//如果D:\file不存在,则以文件的形式创建出来
if (!f1.exists()){
//以文件形式新建
f1.createNewFile();
}
//如果D:\file不存在,则以目录的形式创建出来
if (!f1.exists()){
//以目录形式新建
f1.mkdir();
}
//创建多重目录
File f2 = new File("D:/a/b/c/d");
if (!f2.exists()){
//多重目录的形式新建
f2.mkdirs();
}
File f3 = new File("D:\\百度云盘\\BaiduNetdisk");
//获取文件的父路径
String parentPath = f3.getParent();
System.out.println(parentPath);
File parentFile = f3.getParentFile();
System.out.println("获取绝对路径:" + parentFile.getAbsolutePath());
}
}
代码实例二:
getName(),isDirectory(),isFile(),lastModified(),length()
package IO;
import javax.xml.crypto.Data;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileTest02 {
public static void main(String[] args) {
File f1 = new File("D:\\百度云盘\\BaiduNetdisk");
//获取文件名
System.out.println("文件名:" + f1.getName());
//判断是否是一个目录
System.out.println(f1.isDirectory());
//判断是否是一个文件
System.out.println(f1.isFile());
//获取文件最后一次修改时间
long haoMiao = f1.lastModified();//这个毫秒是从1970年到现在的总毫秒数
//将总毫秒数转换成日期
Date time = new Date(haoMiao);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String strTime = sdf.format(time);
System.out.println(strTime);
//获取文件大小
System.out.println(f1.length());
}
}
代码实例三:
listFiles()方法
package IO;
import java.io.File;
public class FileTest03 {
public static void main(String[] args) {
//获取当前目录下所有的子文件
File f1 = new File("D:\\百度云盘\\BaiduNetdisk");
File[] files = f1.listFiles();
//foreach
for(File file : files){
System.out.println(file.getAbsoluteFile());
System.out.println(file.getName());
}
}
}
2.目录拷贝
将一个文件夹及其中的文档或子文件拷贝从D盘拷到C盘
package IO;
import java.io.*;
public class CopyAll {
public static void main(String[] args) {
//拷贝源
File srcFile = new File("D:\\目录复制演示文件");
//拷贝目标
File destFile = new File("C:\\");
//调用方法拷贝
copyDir(srcFile,destFile);
}
/**
* 拷贝目录
* @param srcFile 拷贝源
* @param destFile 拷贝目标
*/
private static void copyDir(File srcFile, File destFile) {
if(srcFile.isFile()){
//srcFile如果是一个文件的话,递归结束
//是文件的时候需要拷贝
//...一边读一边写
FileInputStream in = null;
FileOutputStream out = null;
try {
//读这个文件
//D:\目录复制演示文件
in = new FileInputStream(srcFile);
//写到这个文件中
//C:\目录复制演示文件
String path = (destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath() + "\\") + srcFile.getAbsolutePath().substring(3);
out = new FileOutputStream(path);
//一边读一边写
byte[] bytes = new byte[1024*1024];//一次复制1MB
int readCount = 0;
while ((readCount = in.read(bytes))!= -1){
out.write(bytes,0,readCount);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
//获取源下面的子目录
File[] files = srcFile.listFiles();
for (File file : files){
//获取所有文件的(包括目录和文件)绝对路径
//System.out.println(file.getAbsolutePath());
if (file.isDirectory()){
//新建对于的目录
//System.out.println(file.getAbsolutePath());
//D:\目录复制演示文件 源目录
//C:\目录复制演示文件 目标目录
String srcDir = file.getAbsolutePath();
String destDir = (destFile.getAbsolutePath().endsWith("\\")?destFile.getAbsolutePath():destFile.getAbsolutePath() + "\\") + srcDir.substring(3);
File newFile = new File(destDir);
if (!newFile.exists()){
newFile.mkdirs();
}
}
//递归调用
copyDir(file,destFile);
}
}
}
3.序列化和反序列化
3.1 概念
序列化:Serialize java对象存储到文件中,将java对象的状态保存下来的过程【objectInputStream】
反序列化:DeSerialize 将硬盘上的数据重新恢复到内存当中,恢复成java对象【objectOutputStream】
3.2 Serializable接口
- 参与序列化和反序列化的对象,必须实现Serializable接口
- 通过源代码发现,Serializable接口只是一个标志接口,这个接口当中什么代码都没有:
public interface Serializable {
}
- Serializable作用:起到标识的作用,标志的作用,java虚拟机看到这个类实现了这个接口,可能会对这个类进行特殊待遇,Serializable这个标志接口是给java虚拟机参考的,java虚拟机看到这个接口之后,会为该类自动生成一个序列化版本号
- 序列化作用:为了保存在内存中的各种对象的状态(也就是实例变量,不是方法),并且可以把保存的对象状态再读出来
3.2.1 序列化
学生类:
package bean;
import java.io.Serializable;
public class Student implements Serializable {
//Java虚拟机看到Serializable接口之后,会自动生成一个序列化版本号
//这里没有手动写出来,java虚拟机会默认提供这个序列化版本号
private int no;
private String name;
public Student() {
}
public Student(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
测试类:
package IO;
import bean.Student;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
/**
* java.io.NotSerializableException student对象不支持序列化!!!
*/
public class ObjectOutputStreamTest01 {
public static void main(String[] args) throws Exception {
//创建java对象
Student s = new Student(1111,"zhangsan");
//序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student"));
//序列化对象
oos.writeObject(s);
//刷新
oos.flush();
//关闭
oos.close();
}
}
运行结果:
生成一个student文件
3.2.2 反序列化
package IO;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class ObjectInputStreamTest01 {
public static void main(String[] args) throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student"));
//开始反序列化,读
Object obj = ois.readObject();
//反序列化回来是一个学生对象,所以会调用学生对象的toString方式
System.out.println(obj);
ois.close();
}
}
运行结果:
3.2.3 序列化多个对象
- 将对象放到序列化集合中
- 参与序列化的ArrayList集合以及集合厚葬的元素User都需要实现java.io.Serializable接口
用户类:
package bean;
import java.io.Serializable;
public class User implements Serializable {
private int no;
private String name;
public User() {
}
public User(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
序列化:
package IO;
import bean.User;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class ObjectOutputStreamTest02 {
public static void main(String[] args) throws Exception{
List<User> userList = new ArrayList<>();
userList.add(new User(1,"zhangsan"));
userList.add(new User(2,"lisi"));
userList.add(new User(3,"wangwu"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users"));
//序列化一个集合,这个集合对象中放了很多其它对象
oos.writeObject(userList);
oos.flush();
oos.close();
}
}
运行结果:
生成一个users文件
反序列化:
package IO;
import bean.User;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.List;
public class ObjectInputStreamTest02 {
public static void main(String[] args) throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("users"));
List<User> userList = (List<User>) ois.readObject();
for(User user : userList){
System.out.println(user);
}
ois.close();
}
}
运行结果:
3.3 transient关键字
表示游离的,不参与序列化
package bean;
import java.io.Serializable;
public class User implements Serializable {
private int no;
//transient关键字表示游离,不参与序列化
private transient String name;//name不参与序列化操作!
public User() {
}
public User(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
运行结果:
重新序列化和反序列化后的
3.4 序列化版本号
- 过了很久,Student这个类源代码改动后,需要重新编译,编译之后生成了全新的字节码文件,并且class文件再次运行的时候,java虚拟机生成的序列化版本号也会发生相应的改变
- Java虚拟机看到Serializable接口之后,会自动生成一个序列化版本号,这里没有手动写出来,java虚拟机会默认提供这个序列化版本号
- java语言中区分类:
第一:首先通过类名进行比对,如果类名不一样,肯定不是同一个类
第二:如果类名一样,再靠序列化版本号进行区分 - 举例
小鹏编写了一个类: com.bjpowernode.java.bean.Student implements Serializable
胡浪编写了一个类: com. bjpowernode.java.bean.Student implements Serializable
不同的人编写了同一个类,但"这两个类确实不是同一个类"”。这个时候序列化版本就起上作用了。
对于java虚拟机来说,java虚拟机是可以区分开这两个类的,因为这两个类都实现了Serializable接口,都有默认的序列化版本号,他们的序列化版本号不一样。所以区分开了。(这是自动生成序列化版本号的好处)
- 自动生成序列化版本号缺点:一旦代码确定之后,不能进行后续的修改,因为只要修改,必然会重新编译,此时会生成全新的序列化版本号,这个时候java虚拟机会认为这是一个全新的类【这样就不好了】
- 注意:凡是一个类实现了Serializable接口,建议将序列化版本号手动的写出来,不建议自动生成;这样,以后这个类即使代码修改了,但是版本号不变,java虚拟机会认为是同一个类
//java虚拟机识别一个类的时候先通过类,如果类名一致,再通过序列化版本号
private static final long serialVersionUID = 1L;
- IDEA自动生成序列化版本号
然后在类名上 Alt+回车键
最终效果:
4.IO和Properties联合使用
IO流:文件的读和写
Properties:是一个Map集合,key和value都是String类型
需求:想将userinfo文件【.txt文件】中的数据加载到Properties对象当中
userinfo文件:
##########在属性配置文件中井号十注释############
#属性配置文件的key重复的话,value会自动覆盖!
#不要有空格!
username=admin
password=123
测试类:
package IO;
import java.io.FileReader;
import java.util.Properties;
public class IoPropertiesTest01 {
public static void main(String[] args) throws Exception{
//新建一个输入流对象
FileReader reader = new FileReader("IO/userinfo");
//新建一个Map集合
Properties pro = new Properties();
//调用Properties对象的load方法将文件中的数据加载到Map集合中
pro.load(reader);//文件中的数据顺着管道加载到Map集合中,其中等号=左边做key,右边做value
//通过key来获取value
String username = pro.getProperty("username");
System.out.println(username);//输出为:admin
}
}
总结:
- 一个非常好的设计理念:以后经常改变的数据,可以单独写到一个文件中,使用程序动态读取,将来只需要修改这个文件的的内容,java代码不需要改动,不需要重新编译,服务器也不需要重启,就可以拿到动态的信息
- 当类似userinfo文件这种文件被称为配置文件,并且当配置文件中的内容格式是如下,把这种配置文件叫做属性配置文件:
key1 = value
key2 = value
- java规范中要求:属性配置文件建议以.properties结尾,但这不是必须的
- 以.properties结尾的文件在java中被称为:属性配置文件
- 其中properties是专门存放属性配置文件内容的一个类