1 IO操作:对象的序列化-Object(Input/Out)Stream
为了将信息通过集合的方式进行本地存储,就需要用到「对象序列化」
使用ObjectInputSteram和ObjectOutputStream类进行文件中对象的读写操作,之后,被序列化的对象需要实现「标记接口Serializable」
问题1.1 修改已经定义好的对象类内部代码
「描述」如果修改了已经定义好的对象类内部代码,那么使用ObjectOutputStream类还可以读出以前储存好的对象吗?
不可以,因为Java虚拟机给每一个标记接口Serializable赋予了UID值,只有在UID相同的情况下,读取才会成功,如果修改了类代码,则旧UID不等于新UID,所以,无法读取。
进一步(专利的味道哈哈),静态的成员变量不会被序列化。
进一步,非静态成员不想被序列化,使用transient关键词声明
问题1.2 静态不能被序列化
因为静态在方法区内存,对象在堆内存中,只序列化堆内存中的内容。
1.3 一个序列化的例子
// 对象存储,对象写,对象读
import java.io.*;
import java.util.*;
public class ObjectDemo {
public static void main(String[] args) throws Exception
{
//writerObj();
readObj();
}
public static void writerObj()throws IOException
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt")); // 写入对象
oos.writeObject(new Person("lisi1",11,"CN"));
oos.close();
}
public static void readObj()throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt")); // 输出对象
Person p = (Person)ois.readObject();
System.out.println(p);
ois.close();
}
}
class Person implements Serializable{ // 标记接口
String name;
int age;
String country;
Person(String name,int age,String country)
{
this.name = name;
this.age = age;
this.country = country;
}
public String toString()
{
return name+":"+age+":"+country;
}
}
2 管道流
管道流的基本功能是,可以进行两个线程间的通信。一个线程作为管道流输出,另一个线程作为管道流输入,将他们连接即可实现通信
场景假设:假设我们不需要多线程需要实现文件的读写,那么在读的管道运行的同时,写的管道也在运行,当出现了用户还没有开始写内容时,写管道就要写入内容时,程序就无法工作,所以需要多线程的协助。
2.1 管道流功能
两大类:PipedInputStream、PipedOutputStream
特点:
(1)通过两大类构建对象
(2)connect进行连接
(3)通常加入多线程,让两个方法同时运行
(4)管道流的read方法是「阻塞式」的,没有读到数据时,方法等待
2.2 多线程IO流对象
//多线程pip
import java.io.*;
class Read implements Runnable
{
private PipedInputStream in;
Read(PipedInputStream in)
{
this.in = in;
}
public void run()
{
try
{
byte[] buf = new byte[1024];
System.out.println("读取前,没有数据,阻塞");
int len = in.read(buf);
System.out.println("读到数据,阻塞结束!");
String s = new String(buf,0,len);
System.out.println(s);
}
catch (Exception e)
{
throw new RuntimeException("管道流读取失败");
}
}
}
class Write implements Runnable{
private PipedOutputStream out;
Write(PipedOutputStream out)
{
this.out = out;
}
public void run()
{
try
{
System.out.println("after 6s will write down some chinese words!");
Thread.sleep(6000);
out.write("我是管道流里的数据,我来了!".getBytes());
}
catch (Exception e)
{
throw new RuntimeException("管道输出流失败!");
}
}
}
class PipedStreamDemo
{
public static void main(String[] args)throws IOException
{
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
in.connect(out); // 连接
Read r = new Read(in);
Write w = new Write(out);
new Thread(w).start();
new Thread(r).start();
}
}
3 文件随机读写 RandomAccessFile 类
该类直接继承Object类,但它是IO体系中的子类,因为具备读写功能,内部存在数组,通过指针对数组元素操作
3.1 RandomAccessFile 类存储、写入
import java.awt.*;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
public static void main(String[] args)throws IOException
{
writeFile();
//readFile();
}
public static void writeFile()throws IOException
{
RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
raf.write("lisi".getBytes());
raf.writeInt(111);
raf.write("王五".getBytes());
raf.writeInt(99);
raf.close();
}
}
public static void readFile() throws IOException
{
RandomAccessFile raf = new RandomAccessFile("ran.txt","r");
raf.seek(8);
byte[] buf = new byte[4];
raf.read(buf);
String name = new String(buf);
int age = raf.readInt();
System.out.println("name = "+name);
System.out.println("age = "+age);
raf.close();
}
}
3.2 RandomAccessFile 中的指针方法seek
随机读写类中定义着数组,可以使用指针方法seek来确定文件读写的位置,通过seek方法,就可以完成对一个文件数据的随机的访问。
3.3 文件操作模式
在RandomAccessFile中进行定义,操作的模式 r w 读与写
3.4 多线程写入例子-资源下载
一个文件可以被随机读写,所以并不需要从头开始进行下载,可以将这个文件在指定位置切分之后进行读写。
4 DataStream类
DataInputStream与DataOutputStream
4.1 DataStream 类介绍
可以用于操作基本数据类型的数据的流对象。
4.2 DataStream写入不同的数据类型
既可以写入整数型、小数型、和布尔型,只需要
import java.io.*;
public class DataStreamDemo {
public static void main(String[] args)throws IOException
{
writeData();
//readData();
}
public static void readData()throws IOException
{
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt")); // 读
int num = dis.readInt();
boolean b = dis.readBoolean();
double d = dis.readDouble();
System.out.println("num="+num);
System.out.println("b="+b);
System.out.println("d="+d);
}
public static void writeData()throws IOException
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt")); // 写
dos.writeInt(234);
dos.writeBoolean(true);
dos.writeDouble(98887.543);
dos.close();
}
}
打印结果:
num=234
b=true
d=98887.543
5 ByteArrayStream 类
5.1 ByteArrayStream 类基本功能
用于操作字节数组的对象流
ByteArrayInputStream :在构造的时候,需要接收数据源,。而且数据源是一个字节数组。
ByteArrayOutputStream: 在构造的时候,不用定义数据目的,因为该对象中已经内部封装了可变长度的字节数组。
这就是数据目的地。
这两个对象操作的都是数组,并没有使用系统资源,所以不需要进行close()关闭。
5.2 ByteArrayStream 类以内存为源和目的操作
// 操作数组
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class byteArrayStream {
public static void main(String[] args) throws IOException
{
ByteArrayInputStream bis = new ByteArrayInputStream("ABCDEFG".getBytes()); // 读
ByteArrayOutputStream bos = new ByteArrayOutputStream(); // 写
int buf = 0;
while ((buf=bis.read())!=-1)
{
bos.write(buf);
}
System.out.println(bos.size());
System.out.println(bos.toString());
bos.writeTo(new FileOutputStream("a.txt"));
}
}
6 字符编码问题
6.1 编码与解码
编码:字符串变为字符数组 String–>byte[ ]; str.getBytes(charsetName);
解码:字节数组变为字符串 byte[ ] -->String: new String(byte[ ],charsetName);
6.2 问题1:客户端与服务器之间的乱码问题
流程图描述为:
7 练习1:实现储存学生信息内容并排序
描述:
需要存储对象
对象信息:姓名、三门课成绩、算出总成绩
需要把学生对象存储到本地文件中
实现:
1,通过获取键盘录入一行数据,并将该行中的信息取出封装成学生对象。
2,因为学生有很多,那么就需要存储,使用到集合。因为要对学生的总分排序。
所以可以使用TreeSet。(实现equals、CompareTo)
3,将集合的信息写入到一个文件中。
import java.io.*;
import java.util.*;
public class StudentInfoDemo {
public static void main(String[] args) throws IOException
{
Comparator<Student> cmp = Collections.reverseOrder(); // 反向比较器
Set<Student> stus = StudentInfoTool.getStudents(cmp);
StudentInfoTool.write2File(stus);
}
}
class Student implements Comparable<Student> // 定义学生类
{
private String name;
private int ma,cn,en;
private int sum;
Student(String name,int ma,int cn,int en)
{
this.name = name;
this.ma = ma;
this.cn = cn;
this.en = en;
sum = ma + cn + en;
}
public int compareTo(Student s) // 实现方法1
{
int num = new Integer(this.sum).compareTo(s.sum);
if(num==0)
return this.name.compareTo(s.name);
return num;
}
public String getName()
{
return name;
}
public int getSum()
{
return sum;
}
public int hashCode()
{
return name.hashCode()+sum*78;
}
public boolean equals(Object obj) // 实现方法2
{
if(!(obj instanceof Student))
throw new ClassCastException("类型不匹配");
Student s = (Student)obj;
return this.name.equals(s.name)&& this.sum==s.sum;
}
public String toString()
{
return "student["+name+","+ma+","+cn+","+en+"]";
}
}
class StudentInfoTool
{
public static Set<Student> getStudents() throws IOException //默认方法
{
return getStudents(null);
}
public static Set<Student> getStudents(Comparator<Student> cmp) throws IOException // 在它的里面进行比较器的判断
{
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); // 键盘写入对象信息
String line = null;
Set<Student> stus = null;
if(cmp==null)
stus = new TreeSet<Student>();
else
stus = new TreeSet<Student>(cmp);
while ((line=bufr.readLine())!=null)
{
if("over".equals(line))
break;
String[] info = line.split(","); // 切割信息
Student stu = new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]));
stus.add(stu); // 添加对象信息
}
bufr.close();
return stus;
}
public static void write2File(Set<Student> stus) throws IOException
{
BufferedWriter bufw = new BufferedWriter(new FileWriter("stuinfo.txt"));
for(Student stu : stus )
{
bufw.write(stu.toString()+"\t");
bufw.write(stu.getSum()+"");
bufw.newLine();
bufw.flush();
}
bufw.close();
}
}