File,序列化,递归复制

1.File

File类可以用来对文件进行操作,增加删除等,但File类却不能访问文件内容,用输入输出流进行访问

1.1常用方法

		//获取文件对象
		File file=new File("");
		//判断文件是否存在
		file.exists();
		//判断是否为文件,判断是否为目录
		file.isFile();
		file.isDirectory();
		//创建文件
		file.createNewFile();
		//删除文件,如果改文件如果有子文件,则删除失败
		file.delete();
		//只要文件存在,便会删除此文件
		file.deleteOnExit();
		//获取文件的绝对路径
		file.getAbsolutePath();
		//获取问价的名字+后缀名
		file.getName();
		//获取父文件、String
		file.getParent();
		//获取父文件对象
		file.getParentFile();
		//获取文件的所有子文件对象(直接子文件)
		file.listFiles();
		//创建文件目录,不加s,则只创建不存在的目录的最后一个包含文件的目录
		file.mkdirs();
		//  根据系统不同是不同的斜杠 
		String se=file.separator;

1.2递归复制

当递归复制文件,要慎重

	public static void main(String[] args) {
		copy(new File("D:/train/day1/copy.txt"), "D:/train/day1/temp");
	}
//拼接目录
	static String directory = "";	
public static void copy(File srcFile, String destDirectory) {
		// 判断文件是否为目录
		if (srcFile.isDirectory()) {
			directory += "/" + srcFile.getName();
			File[] files = srcFile.listFiles();
			for (File f : files) {
				copy(f, destDirectory);
			}
		} else {
			// 先获取源文件路径
			String filePath = srcFile.getAbsolutePath();
			// 获取目标文件路径,如果不存在则创建
			String newFilePath = destDirectory + directory + "/" + srcFile.getName();
			File newFile = new File(newFilePath);
			System.out.println(newFilePath);
			// 创建目录
			if (!newFile.getParentFile().exists()) {
				newFile.getParentFile().mkdirs();
			}
			// 开始复制文件
			try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
					BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFilePath));) {
				byte[] bytes = new byte[bis.available()];
				int len;
				while ((len = bis.read(bytes)) != -1) {
					bos.write(bytes, 0, len);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

2.序列化

序列化:把堆内存中的对象持久化地保存再本地磁盘中,把对象数据转换成二进制流进行存储

反序列化:与序列化相反,将磁盘中的持久化对象反序列化到堆内存中

可长期存储,有利于数据传输,不序列化,不能进行长期存储和网络传递

		// 序列化
		User u = new User(18, "藏三");
		try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./src/user"));) {
			oos.writeObject(u);
			oos.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
//反序列化		
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./src/user"));) {
			User us = (User) ois.readObject();
			System.out.println(us.getName());
		} catch (IOException e) {
			e.printStackTrace();
		}

2.1 对象流

ObjectInputStream,ObjectOutputStream,用于对对象进行序列化与反序列化

2.2 serialVersionUID

版本号,每次修改类时,版本号也会随之更改,而当如果版本号不一致则会报错,所以可以自己添加一个版本号常量进行指定。

2.3 transient

修饰的属性不会被序列化,不能修饰方法。而当把不必要的数据进行修饰时,则会提高序列化与反序列化的效率

注意: 序列化的类要实现Serializable接口,否则报异常

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值