目录
心情日记
学IO流的第一感觉就是代码单词是真的长,而且IO流这块抛的异常遍地都是。下午发烧一下午(不是冠上了),头疼欲裂!!!勉强听完课,结果越来越裂。。。下了自习直接回宿舍睡觉。
重点归纳
- IO流
- 序列化与反序列化
知识点及解析
IO流
File类:只能操作文件,不能操作文件的内容
想要更改文件的内容就需要IO流(输入输出流)
流的分类
1.按照流向分
输入流:从硬盘上读取数据到内存(读)
输出流:从内存写出数据到硬盘(写)一个文件在传输过程中经历了多次的拷贝,IO的性能本身就很低
所以诞生了新技术:
零拷贝、Nio(新技术)
2.按照操作单元分
字节流:一个字节一个字节的操作。二进制操作。可以操作任意类型的文件
字符流:一个字符一个字符的操作。一个字符两个字节,主要用来处理文本文件
常见文本文件:.txt、.java、.py、.xml、.properties、.html、.css、.js
3.按照角色划分
节点流:直接操作一个特定的IO设备。(把手抓饼直接给你)
处理流:在节点流的基础上做进一步的处理。(把手抓饼装袋子里给你)
开发中一般用处理流,性能高,代码简单
Java中输入/输出常用的流:
字节输入流 字节输入流 字符的输入流 字符输出流
抽象基类 InputStream OutputStream Reader Writer
访问文件 FileInputStream FileOutputStream FileReader FileWriter
(节点流)
缓冲流 BufferedInputStream BufferedOutputStream BufferedReader Buffered Writer
(处理流)
操作对象 ObjectInputStream ObjectOutputStream没有:ObjectReader ObjectWriter
File类不能够操作文件的内容
顶级的字符输入流的基类Reader
//创建一个文件
public static void main(String[] args) {
File file = new File("e:/aaa.txt");
try {
file.createNewFile();
System.out.println("文件创建完成!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
流到底怎么用?
字节输入流(read)
1.创建一个FileInputStream对象
2.定义一个标记,用来控制输入流的读取
3.通过循环读取,如果读取到了-1,说明读取到了文件的末尾,循环结束
4.关闭资源。*****
关闭流是5*重要级别的可以封装成一个类去使用:
/*
关流的工具类
*/
import java.io.*;
import java.util.Objects;
public class IOUtil {
public static void closeIO(Reader reader, Writer writer){
if(Objects.nonNull(reader)) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(Objects.nonNull(writer)){
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void closeIO(InputStream inputStream, OutputStream outputStream) {
if(Objects.nonNull(inputStream)) {
try {
inputStream.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if(Objects.nonNull(outputStream)){
try {
outputStream.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
注意:一个流读完就不能再读了
流读完之后系统自动调用mark和reset方法,
记录这个流读到哪个位置,再次读这个流时重置到上次记录的读完的位置
所以就无法再次读取内容,并不是读完一次就关闭了流
//test01怎么用字节输入流读数据
@Test
public void test01() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream("e:/aaa.txt");
// 开始读的操作,read方法,返回值是int,当返回值为-1时,说明文件读取到了末尾
// 读取文件是否结束的标记
int read;
// 字节流读数据的时候一个字节一个字节去读
// 循环读取
while((read = inputStream.read()) != -1) {
System.out.print(read + " ");
}
System.out.println();
System.out.println("读取完毕,再读一次。。。。");
// 字节流读数据的时候一个字节一个字节去读
// 循环读取
while((read = inputStream.read()) != -1) {
System.out.print(read + " ");
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
// 关闭流
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
还有一个read方式:
读的时候放进数组中,不是一个一个字节去读,而是按一个数组的长度去读-----这就叫缓冲
test02加了一个缓冲区,性能、效率比test01高,开发中一般用test02
@Test
public void test02() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream("e:/aaa.txt");
int read;
byte [] buf = new byte[1024];
while((read = inputStream.read(buf)) != -1) {
// System.out.print(Arrays.toString(buf) + " ");
System.out.println(new String(buf));
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//用工具包关流
IOUtil.closeIO(inputStream,null);
//手动关流
// try {
// if(Objects.nonNull(inputStream)){
// // 关闭流
// inputStream.close();
// }
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
}
}
字节输出流(write)
用法和输入流差不多
FileOutputStream构造器;
boolean append为参数的构造器:如果传入true,则代表在原有基础上追加,不覆盖
如果传入false,或者不传,覆盖原有内容*****写的操作目标文件如果不存在,会自动创建出来。
多个流同时使用时
先开的流先关,后开的流后关,开关指的是使用
//字节输出流的方法,直接上例子
@Test
public void test01() {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream("e:/aaa.txt",true);
// 一个字节一个字节的写
outputStream.write(98);
System.out.println("数据写出成功...");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Test
public void test02() {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream("e:/aaa.txt",true);
// 一个字节一个字节的写
//转义字符换行
outputStream.write("\r\n".getBytes());
//写出去的内容
outputStream.write("八月正午的阳光都没你耀眼".getBytes());
System.out.println("数据写出成功...");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//工具类关流
IOUtil.closeIO(null,outputStream);
//手动关流
// try {
// if(Objects.nonNull(outputStream)){
// outputStream.close();
// }
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
}
}
练习:文件的复制
两个流:
FileInputStream:把对应文件的内容读取出来
FileOutputStream:把读到的内容写出去read(byte[])
write(byte[])
@Test
public void test01(){
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream("E:\\workspace\\vscode\\HTML\\20220709\\img\\lijian.jpeg");
outputStream = new FileOutputStream("e:/lijian.jpeg");
byte [] buf = new byte[3];
int len;
// 循环读进来
while((len = inputStream.read(buf)) != -1){
// 写出去
outputStream.write(buf,0,len);
}
System.out.println("文件复制完毕...");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//工具类关流
// IOUtil.closeIO(inputStream,outputStream);
//手动关流
try {
//完善关流,如果流未开始操作,不用关了
if(Objects.nonNull(outputStream)){
outputStream.close();
int i = 10 / 0;
}
} catch (Exception e) {
//建议用大异常抓
throw new RuntimeException(e);
}
try {
if(Objects.nonNull(inputStream)){
inputStream.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
字符流
reader/writer
test01字符输入流
@Test
public void test01() {
Reader reader = null;
try {
reader = new FileReader("e:/aaa.txt");
int len;
char [] buf = new char[10];
while((len = reader.read(buf)) != -1){
System.out.println(new String(buf,0,len));
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtil.closeIO(reader,null);
}
}
test02输出流
@Test
public void test02() {
Writer writer = null;
try {
writer = new FileWriter("e:/bbb.txt");
writer.write("阿里巴巴规约手册...");
System.out.println("数据写出成功...");
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
IOUtil.closeIO(null,writer);
}
}
字符处理流(用的最多)
直接操作字符串,只能处理纯文本文件:
.txt,.java,.html,.css.........如果要操作纯文本文件,一定用的是字符处理流的缓冲流
边读边写时:
外层流,内层流,关闭了外层的流,内层的流会随之关闭。
test01缓冲字符输入流
readline,一行一行读,读字符串
@Test
public void test01() {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("e:/aaa.txt"));
String str;
while((str = bufferedReader.readLine()) != null) {
System.out.println(str);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtil.closeIO(bufferedReader,null);
}
}
test02缓冲字符输出流
@Test
public void test02() {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter("e:/xxx.txt"));
bufferedWriter.write("今天是星期二,天气凉爽!");
System.out.println("数据写出成功!");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtil.closeIO(null,bufferedWriter);
}
}
序列化与反序列化
在一个User类的基础上展开学习:
import java.io.Serializable;
public class User implements Serializable {
// 序列化的版本号
private static final long serialVersionUID = -6884553706620141921L;
private String name;
private Integer age;
private Integer gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public User() {
}
public User(String name, Integer age, Integer gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", gender=" + gender +
'}';
}
}
序列化
将对象写入IO流中,将内存模型的对象变成字节数字,可以进行储存和传输
@Test
public void test02() {
ObjectInputStream objectInputStream = null;
// 先锁定一个文件
try {
objectInputStream = new ObjectInputStream(new FileInputStream("e:/user.txt"));
User user = (User) objectInputStream.readObject();
System.out.println("对象读取成功:" + user);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} finally {
IOUtil.closeIO(objectInputStream,null);
}
}
反序列化
从IO流中恢复对象,将储存在硬盘上或者从网络中接收到数据恢复成对象模型。(序列化的逆操作)
@Test
public void test01() {
ObjectOutputStream objectOutputStream = null;
// 先锁定一个文件
try {
objectOutputStream = new ObjectOutputStream(new FileOutputStream("e:/user.txt"));
User user = new User("张三",25,1);
objectOutputStream.writeObject(user);
System.out.println("对象写出成功...");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtil.closeIO(null,objectOutputStream);
}
}
使用场景
所有可在网络上传输的对象都必须是可序列化的,
否则会报错,所有保存在硬盘上的对象也必须要可序列化。
序列化版本号
反序列化必须拥有.class文件,随着项目的升级,class文件也会升级,会导致写出去的User类和读回来的User类不匹配,所以序列化要保证升级前后的兼容性。
所以Java提供了版本号的概念,
版本号可以随意指定,如果不指定,JVM会根据类信息计算一个版本号 所以无法匹配--报错不指定版本号不利于JVM的移植
不同的JVM计算规则不同,class文件没有改也会导致无法反序列化如果修改了方法,反序列化不受影响,不需要改变版本号
修改静态变量、瞬态变量、反序列化不受影响
其他的不行。
总结
1.所有需要网络传输的对象都需要实现序列化接口
2.对象的类名、实例变量都会被序列化;方法、类变量、transient变量不会被序列化
3.如果想让某个变量不被序列化,可以用transient修饰
4.序列化对象的引用类型成员变量,也必须是可序列化的,否则会报错
5.反序列化时必须有序列化对象的class文件
6.同一个对象被序列化多次,只有第一次序列化为二进制流,以后都只是保存序列化的版本号
7.建议所有可序列化的类加上版本号,方便项目升级。
我们最终会把所有的.class文件打包,把这个包部署到服务器上。
从始至终,.java仅仅是我们程序员写的,给程序员看的。
.java甚至不会参与到打包中,不会出现在服务器上。运维人员去服务器部署项目,部署的就是一堆的.class。
我们的.properties属性文件是不参与编译的。
public static void main(String[] args) throws IOException {
File file = new File("db.properties");
// file.createNewFile();
Properties properties = new Properties();
properties.load(new FileInputStream(file));
System.out.println(properties.getProperty("username"));
}
作业及解答
创建一个商店,更新商店商品列表文件,列表格式为:商品编号+ 空格+商品名称+空格+商品价格
(其实就是对文件中内容的增删改查,各种读流写流关流)
商品类(商品个体属性):
public class Goods {
private Integer id;
private String name;
private Integer price;
public Goods() {
}
public Goods(Integer id, String name, Integer price) {
this.id = id;
this.name = name;
this.price = price;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
商店类(增删改查):
import com.jsoft.Util.IOUtil;
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class Shop {
private static List<Goods> list = new ArrayList<>(16);
private static BufferedReader reader = null;
private static BufferedWriter writer = null;
public static void insert(Scanner sc) {
System.out.println("请输入商品编号:");
Integer id = sc.nextInt();
System.out.println("请输入商品名:");
String name = sc.next();
System.out.println("请输入商品价格:");
Integer price = sc.nextInt();
// 最简单,直接追加
try {
writer = new BufferedWriter(new FileWriter("d:\\test.txt",true));
writer.write(id + " " +name + " " + price);
writer.newLine();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("添加成功!");
}
public static void delete(Scanner sc) {
System.out.println("请输入商品编号:");
// 全部拿出来,删除后覆盖
int id = sc.nextInt();
try {
reader = new BufferedReader(new FileReader("d:\\test.txt"));
String str;
while((str = reader.readLine()) != null){
String[] s = str.split(" ");
Goods goods = new Goods(Integer.parseInt(s[0]),s[1],Integer.parseInt(s[2]));
list.add(goods);
}
// 输出流的实例化的位置!!!
writer = new BufferedWriter(new FileWriter("d:\\test.txt"));
Iterator<Goods> iterator = list.iterator();
while(iterator.hasNext()) {
Goods goods = iterator.next();
if(id == goods.getId()){
iterator.remove();
}
}
for (Goods goods : list) {
writer.write(goods.getId() + " " + goods.getName() + " " + goods.getPrice());
writer.newLine();
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtil.closeIO(reader,writer);
}
System.out.println("删除成功!");
}
public static void update(Scanner sc) throws IOException {
// 全部拿出来,更新后覆盖
try {
reader = new BufferedReader(new FileReader("D:/test.txt"));
String str;
while (((str = reader.readLine()) != null)) {
String[] s = str.split(" ");
Goods goods = new Goods(Integer.parseInt(s[0]),s[1],Integer.parseInt(s[2]));
list.add(goods);
}
System.out.println("请输入商品编号:");
int id = sc.nextInt();
System.out.println("输入新的商品名称");
String name = sc.next();
System.out.println("输入新的价格");
int price = sc.nextInt();
Iterator<Goods> iterator = list.iterator();
while(iterator.hasNext()) {
Goods goods = iterator.next();
if(id == goods.getId()){
goods.setId(id);
goods.setName(name);
goods.setPrice(price);
System.out.println("修改成功");
System.out.println(goods);
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
}
try {
writer = new BufferedWriter(new FileWriter("D:/test.txt"));
for (Goods goods : list) {
writer.write(goods.getId().toString()+" "+goods.getName()+ " " + goods.getPrice().toString());
writer.newLine();
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
reader.close();
writer.close();
}
}
public static void findOne(Scanner sc) {
System.out.println("请输入商品编号:");
int id = sc.nextInt();
String line;
try {
reader = new BufferedReader(new FileReader("D:/test.txt"));
while ((line = reader.readLine())!=null){
String[] str = line.split(" ");
if (Integer.parseInt(str[0]) == id) {
System.out.println(line);
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
reader.close();
} catch (IOException e) {
}
}
}
}
测试类(操作系统):
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
main:while (true) {
System.out.println("请选择功能:1、插入新商品 2、删除商品 3、修改商品 4、查找一个商品 5、退出");
String flag = scanner.next();
switch (flag) {
case "1":
Shop.insert(scanner);
break;
case "2":
Shop.delete(scanner);
break;
case "3":
try {
Shop.update(scanner);
} catch (IOException e) {
e.printStackTrace();
}
break;
case "4":
Shop.findOne(scanner);
break;
case "5":
System.out.println("系统退出...");
break main;
}
}
}
}