aObjectStream_ObjectInPutStreamDemo02
package com.se.aObjectStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* 反序列化的类型:
* ObjectInputStream(InputStream is)
*
* 知识拓展:
* 1. 序列化时,程序每执行一次都会在开始的地方先写一个流头。如果是追加模式,那么文件中,可能有多个流头
* 2. 反序列化时,也就是读取文件的时候,默认只读取一次流头,其余都是对象信息,
* 所以有多个流头,可能是会将除第一个流头以外的流头都读取了为对象信息进行解析
* 3. 会报异常: java.io.StreamCorruptedException: invalid type code:AC
*/
public class ObjectInPutStreamDemo02 {
public static void main(String[] args) {
//创建一个反序列化的流对象
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream("./student.s"),4096));
//反序列化
Object obj = ois.readObject();
System.out.println(obj);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
aObjectStream_ObjectOutPutStreamDemo01
package com.se.aObjectStream;
import java.io.*;
import java.util.Objects;
/**
* 序列化: 内存中的对象转成字节数组,这个过程就是序列化,序列化的目的是存储或者传输
* 反序列化: 字节数组转成内存中的对象,这个过程就是反序列化,反序列化的目的是读取或者传输
* <p>
* tips: 字节数组就是字节序列的意思
* 序列化:ObjectOutputStream
*/
public class ObjectOutPutStreamDemo01 {
public static void main(String[] args) {
//创建一个学生
Student student = new Student("小米", 18, '男');
//使用对象输出流,将学生写出文件中
ObjectOutputStream ois = null;
try {
ois = new ObjectOutputStream(
new BufferedOutputStream(
//流的构造器的相对路径,相对的是Project的根目录
new FileOutputStream("./student.s", true), 4096));
//写出对象
ois.writeObject(student);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
自定义的类型,如果想要将其对象进行存储或者传输,那么这个类必须要实现一个接口
这个接口就是Serializable
该接口里面什么的没有东西,就是标识,标识这个类是可以被序列化的
seraiVersionUID:序列化的版本号
1. 在序列化时,系统会默认给该类提供一个序列化版本号。
当反序列化时,系统会先读取该类的序列化版本号,然后与反序列化版本号进行比较,
如果版本号相同,则认为两个版本是相同的,可以进行反序列化。
如果版本号不同,则认为两个版本是不同的,不能进行反序列化,报异常,版本不兼容
注意: 系统提供的版本号,可能会发生变化,不同时间点的序列化版本号可能不同
2. 为了避免上述情况,程序员应该主动提供一个固定的版本号
这样序列化和反序列化的版本号是相同的,就不错出现异常
*/
class Student implements Comparable<Student>, Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private char gender;
public Student() {
}
public Student(String name, int age, char gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", gender=" + gender +
'}';
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Student student = (Student) object;
return age == student.age && gender == student.gender && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, gender);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
@Override
public int compareTo(Student o) {
return o.age - this.age;
}
}
aObjectStream_ObjectOutPutStreamDemo02
package com.se.aObjectStream;
import java.io.*;
import java.util.Objects;
public class ObjectOutPutStreamDemo02 {
public static void main(String[] args) {
// 创建对象
Teacher t = new Teacher("张三", 18, "北京", "我是备注");
//序列化Teacher对象
serialObject(t);
// 反序列化对象并打印
Teacher t1 = deserializeTeacher();
System.out.println(t1);
}
//序列化对象
public static void serialObject(Object obj) {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new BufferedOutputStream(
new FileOutputStream("./teacher.txt"), 4096));
oos.writeObject(obj);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//反序列化对象
public static Teacher deserializeTeacher() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream("./teacher.txt"), 4096));
//读取对象
Object obj = ois.readObject();
if (obj instanceof Teacher) {
return (Teacher) obj;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ois.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return null;
}
}
class Teacher implements Serializable, Comparable<Teacher> {
public static final long serialVersionUID = 1L;
private String name;
private int age;
private String address;
private transient String remark;
public Teacher() {
}
public Teacher(String name, int age, String address, String remark) {
this.name = name;
this.age = age;
this.address = address;
this.remark = remark;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Teacher teacher = (Teacher) object;
return age == teacher.age && address == teacher.address && Objects.equals(name, teacher.name) && Objects.equals(remark, teacher.remark);
}
@Override
public int hashCode() {
return Objects.hash(name, age, address, remark);
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", age=" + age +
", address=" + address +
", remark='" + remark + '\'' +
'}';
}
@Override
public int compareTo(Teacher o) {
return 0;
}
}
bWriterAndReader_01WriterDemo
package com.se.bWriterAndReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
/**
* 字符输出流:
* 1. 抽象父类 Writer
* 2. 书写底层,以一个char为单位
* 3. 底层依然是字节流
* 4. 基本的字符流,我们称为转换流,因为涉及到字符与字节之间的转换所使用的编码集
* 5. 在编写时的字符集,默认使用的是UTF-8, 字母是一个字节,汉字是三个字节。
* 6. OutputStreamWriter(OutputStream os)
* OutputStreamWriter(OutputStream os, String charsetName)
*/
public class _01WriterDemo {
public static void main(String[] args) {
OutputStreamWriter osw = null;
try {
osw = new OutputStreamWriter(
//常用的字符集编码 UTF-8 GBK GB2312 GB18030 UNICODE
//ISO-8859-1: HTTP通信时使用
new FileOutputStream("./test07/char.txt"));
//写一个字符
osw.write("中");
//写一个字符组
char[] chars = {'国', '欢', '迎', '你'};
osw.write(chars);
//将chs中的后三个再写一次
osw.write(chars, chars.length - 3, 3);
//将一个字符串写出
osw.write("你好");
//如果有缓冲,冲刷,强制写出
osw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
osw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
bWriterAndReader_02ReaderDemo
package com.se.bWriterAndReader;
import java.io.*;
/**
* 字符转换输入流:
* InputStreamReader(InputStream os)
* InputStreamReader(InputStream os,String charsetname)
*/
public class _02ReaderDemo {
public static void main(String[] args) {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(
new FileInputStream("./test07/char.txt"), "GB2312");
//读取一个字符
for (int i = 0; i < 6; i++) {
char ch = (char) isr.read();
System.out.println("ch:" + ch);
}
//继续读取10个字符
char[] chs = new char[10];
int len;
while ((len = isr.read(chs)) != -1) {
System.out.println("chs:" + new String(chs, 0, len));
System.out.println("len:" + len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
cBufferedChar_01PrintWrierDemo
package com.se.cBufferedChar;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
/**
* 缓冲字符输出流:
* 1. 一般使用PrintWriter这个子类,不适用BufferedWriter
* 2. PrintWriter这个类的构造器比较丰富
* -PrintWriter(File file)
* -PrintWriter(String pathname)
* -PrintWriter(OutputStream os)
* -PrintWriter(OutputStream os,boolean autoFlush)
* -PrintWriter(Writer writer)
* -PrintWriter(Writer writer,boolean autoFlush)
* 3. 内部也是维护了一个字符缓冲区
* 写的时候,先写到缓冲区,缓冲区满了再一次性写入文件
* 不过,当使用的自动行刷新功能,每写一行,然后在行尾添加换行符,强制写出
* 4. 除了write方法,还提供了print和println的各种重载方法
*/
public class _01PrintWriterDemo {
public static void main(String[] args) {
try (PrintWriter pw = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream("test07/char.txt"),"GBK"),true)){
//写出一个字符数组
char[] charArray = "你好,中国".toCharArray();
pw.write(charArray);
//调用print方法,写出去"请从绝处"
pw.print("请从绝处");//print 没有行刷新效果
//调用println方法,写出去"读我侠义"
//当构造器里面指定行刷新功能,设定为true,此时println才会在行尾添加换行符,强制写出
pw.println("读我侠义");
Thread.sleep(30000);
}catch (Exception e){
e.printStackTrace();
}
}
}
cBufferedChar_02BufferedReaderDemo
package com.se.cBufferedChar;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
/**
* 字符缓冲流
* 1. 内部也提供了一个缓冲区,尽可能一次性读取,存满缓存区。
* 2. 程序员调用读取方法,从缓冲区中获取数据,当获取完数据后,缓冲区再次从文件中尽可能一次性读取数据
* 3. BufferedReader(Reader reader)
* 4. 常用方法是readline(): 读取一行数据,只读取到换行符,但是读取的数据不含换行符
*/
public class _02BufferedReaderDemo {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream("test07/char.txt"), "GBK"))) {
char ch = (char) br.read();
System.out.println("ch:" + ch);
// 读取一行数据
String s;
while ((s = br.readLine()) != null) {
System.out.println("s:" + s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
cBufferedChar_03FileWriterDemo
package com.se.cBufferedChar;
import java.io.FileWriter;
/**
* FileWriter: 文件输出流
* 1. 相当于OutputStreamWriter和FileOutputStream的组合,但是不能指定字符集
* 2. 构造器:
* FileWriter(File file)
* FileWriter(String file,boolean append)
* FileWriter(String pathname)
* FileWriter(String pathname,boolean append)
* 3. 常用方法: 就是转换流的方法
*/
public class _03FileWriterDemo {
public static void main(String[] args) {
try (FileWriter fw = new FileWriter("./test07/char.txt")) {
fw.write("有时明月无人夜");
fw.write("独向昭潭制恶龙");
// 追加
fw.append("请从绝处,读我侠义");
} catch (Exception e) {
e.printStackTrace();
}
}
}
cBufferedChar_04FileReaderDemo
package com.se.cBufferedChar;
import java.io.FileReader;
/**
* 文件输出流: FileReader
* 1. 相当于InputStreamReader和FileInputStream的组合,不能指定字符集
* 2. 构造器:
* FileReader(File file)
* FileReader(String fileName)
* 3. 常用方法:也与转换流一致
*/
public class _04FileReaderDemo {
public static void main(String[] args) {
try (FileReader fr = new FileReader("test07/char.txt")) {
int ch = fr.read();
System.out.println((char) ch);
char[] chs = new char[100];
int len = -1;
while ((len = fr.read(chs)) != -1) {
System.out.println(new String(chs, 0, len));
System.out.println(len);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
dOher_01SystemDemo
package com.se.dOther;
import java.io.*;
import java.util.Scanner;
/**
* system: 系统类,里面封装了一些本地方法和静态属性
* 1. 静态属性:
* PrintStream out: 标准输出流,默认目的地是控制台console
* PrintStream err: 标准错误输出流,默认目的地是控制台console
* InputStream in: 标准输入流,默认数据源是控制台console
*/
public class _01SystemDemo {
public static void main(String[] args) throws IOException {
testSystemIn();
}
/**
* 测试System.in
* @throws IOException
*/
public static void testSystemIn() throws IOException {
//将Sysyem.in临时报错到一个变量中
InputStream is = System.in;
FileInputStream fis = new FileInputStream("test07/char.txt");
//将数据源从控制台来为指定文件
System.setIn(fis);
//使用扫描类
Scanner sc = new Scanner(System.in);
//与迭代器类似,先问是否有下一行
while (sc.hasNext()){
//取一行数据
String s = sc.nextLine();
System.out.println(s);
}
}
/**
* 测试System.out
* @throws FileNotFoundException
*/
public static void testSystemOut() throws FileNotFoundException {
/**
* System.out: 返回一个标准输出流对象
* 调用println方法: 即调用的是PrintStream的方法,将数据打印到控制台
*/
System.out.println("hello world");
/*
修改out这个流的目的地。
1. 将默认的目的地,临时保存起来
*/
PrintStream ps = System.out;
//使用IO流,来重新定位
PrintStream pw = new PrintStream("test07/char.txt");
//将上述的流对象,赋值给System的out属性
System.setOut(pw);
//调用out的println方法,将数据打印到文件
System.out.println("哈基米");
//改回
System.setOut(ps);
System.out.println("i'm back");
}
}
zExercise_Exercise01
package com.se.zExercise;
import java.io.*;
public class Exercise01 {
public static void main(String[] args) {
// 测试1: 调用copyFile1方法,copy一个纯文本文件
copyFile1(new File("./dir11/a.txt"), new File("./dir11/a.txt"));
// 测试2: 调用copyFile1方法,copy一个视频文件
copyFile1(new File("./dir11/a.mp4"), new File("./dir11/b.mp4"));
// 测试3: 调用copyFile2方法,copy一个纯文本文件
copyFile2(new File("./dir12/a.txt"), new File("./dir12/a.txt"));
// 测试4: 调用copyFile2方法,copy一个视频文件
copyFile2(new File("./dir12/a.mp4"), new File("./dir12/b.mp4"));
}
public static void copyFile1(File fromFile, File toFile) {
try (FileInputStream fis = new FileInputStream(fromFile);
FileOutputStream fos = new FileOutputStream(toFile);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
byte[] buffer = new byte[1024];
int length;
while ((length = bis.read(buffer)) > 0) {
bos.write(buffer, 0, length);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void copyFile2(File fromFile, File toFile) {
try (FileReader fr = new FileReader(fromFile);
FileWriter fw = new FileWriter(toFile)) {
char[] buffer = new char[1024];
int length;
while ((length = fr.read(buffer)) > 0) {
fw.write(buffer, 0, length);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
标签:String,age,day07,new,javase,序列化,public,name
From: https://blog.csdn.net/m0_64370841/article/details/141333012