黑马程序员-IO流(对象序列化、RandomAccessFile 类、字符编码)

-----------android培训java培训、java学习型技术博客、期待与您交流! ------------


一、对象序列化

ObjectOutputStram和ObjectInputStream

 

1、概述:

将堆内存中的对象存入硬盘,保留对象中的数据,称之为对象的持久化(或序列化)

2、特有方法:

    write(int val)   --->  写入一个字节(最低八位)
    writeInt(int vale)  --->   写入一个32位int值

3、使用步骤:


(1)写入流对象:

1)创建对象写入流,与文件关联,即传入目的
2)通过写入writeObject()方法,将对象作为参数传入,即可写入文件

(2)读取流对象

1)创建对象读取流,与文件关联,即传入源
2)通过writeObject()方法,读取文件中的对象,并返回这个对象

4、说明:serialVersion

a、给类一个可被编译器识别的的序列号,在编译类时,会分配一个long型UID,通过序列号,将类存入硬盘中,并序列化,即持久化。序列号根据成员算出的。静态不能被序列化。如果非静态成员也无需序列化,可以用transien修饰。
代码示例:

b、接口Serializable中没有方法,称之为标记接口

 

5、代码示例:

import java.io.*;

//创建Person类,实现序列化  
class Person implements Serializable {
	// 定义自身的序列化方式
	public static final long serialVersionUID = 42L;
	// 定义私有属性
	private String name;
	private int age;
	transient String id;
	String country = "cn";

	// 构造Person类
	Person(String name, int age, String id, String country) {
		this.name = name;
		this.age = age;
		this.id = id;
		this.country = country;
	}

	// 覆写toString方法
	public String toString() {
		return name + ":" + age + ":" + id + ":" + country;
	}
}

// 对象序列化测试
class ObjectStreamDemo {
	public static void main(String[] args) {
		// 对象写入流
		writeObj();
		// 对象读取流
		readObj();
	}

	// 定义对象读取流
	public static void readObj() {
		ObjectInputStream ois = null;
		try {
			// 创建对象读取流
			ois = new ObjectInputStream(new FileInputStream("obj.txt"));
			// 通过读取文件数据,返回对象
			Person p = (Person) ois.readObject();
			System.out.println(p);
		} catch (Exception e) {
			throw new RuntimeException("写入文件失败");
		}
		// 最终关闭流对象
		finally {
			try {
				if (ois != null)
					ois.close();
			} catch (IOException e) {
				throw new RuntimeException("写入流关闭失败");
			}
		}
	}

	// 定义对象写入流
	public static void writeObj() {
		ObjectOutputStream oos = null;
		try {
			// 创建对象写入流
			oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));
			// 写入对象数据
			oos.writeObject(new Person("lisi", 25, "01", "cn"));
		} catch (Exception e) {
			throw new RuntimeException("写入文件失败");
		}
		// 关闭流资源
		finally {
			try {
				if (oos != null)
					oos.close();
			} catch (IOException e) {
				throw new RuntimeException("写入流关闭失败");
			}
		}
	}
}



二、RandomAccessFile 类(重要!!!)



1、概述:



(1)自身具备读写方法(很牛逼!又可以读又可以写)
(2)通过skipByte(int x)和seek(int x)来达到随机访问文件
(3)该类不是IO体系子类,而是直接继承Object,但它是IO包中的成员,因为它具备读写方法
(4)该类内部封装了数组,而且通过指针对数组的元素进行操作,可以通过getFilePoint获取指针位置,同时可以通过seek改变指针位置
(5)该类可以完成读写的原理是:内部封装了字节输入输出流
(6)构造函数:RandomAccessFile(File file,String mode),RandomAccessFile(String name, String mode),可已从它的构造函数中看出,该类只能操作文件(也有字符串),而且操作文件还有模式。
          模式传入值:”r“:以只读方式打开;”rw“:打开以便读写
          如果模式为只读,则不会创建文件,会去读一个已存在的文件,若文件不存在,则会出现异常,如果模式为rw,且该对象的构造函数要操作的文件不存在,会自动创建,如果存在,则不会覆盖,也可通过seek方法修改。
(7)可用于多线程分段写入,即:下载原理

 

2、特有方法:

(1)seek(int n):设置指针,可以将指针设置到前面或后面
(2)skipBytes(int n):跳过指定字节数,不可往前跳

3、使用步骤:

(1)创建RandomAccessFile对象
(2)将数据写入到指定文件中
(3)读取数据,读入到指定文件中

注意:要读取后面的数据,需要调用数组指针,通过改变角标位置,取出相应的数据,即:
           a.调整对象的指针:seek()
           b.跳过指定字节数

4、代码示例:

import java.io.*;

//注:这几个函数内部都需要try,为测试,在函数上抛异常  
class RanAccFileDemo {
	public static void main(String[] args) throws IOException {
		// readRaf();
		readRaf2();
		// writeRaf();
	}

	// 写入数据
	public static void writeRaf() throws IOException {
		// 创建对象,写入数据
		RandomAccessFile raf = new RandomAccessFile("ran.txt", "rw");
		raf.write("王五".getBytes());
		raf.writeInt(99);
		raf.write("李四".getBytes());
		raf.writeInt(97);
		raf.close();
	}

	// 读取数据
	public static void readRaf() throws IOException {
		// 创建对象,读取数据
		RandomAccessFile raf = new RandomAccessFile("ran.txt", "r");
		byte[] b = new byte[4];
		raf.read(b);
		String name = new String(b);
		int age = raf.readInt();
		System.out.println("name=" + name);
		System.out.println("age=" + age);
		raf.close();
	}

	// 读取数据
	public static void readRaf2() throws IOException {
		// 创建对象,读取数据
		RandomAccessFile raf = new RandomAccessFile("ran.txt", "r");
		// 调整对象中的指针
		// raf.seek(8);
		// 跳过指定字节数
		raf.skipBytes(8);
		byte[] b = new byte[4];
		raf.read(b);
		String name = new String(b);
		int age = raf.readInt();
		System.out.println("name=" + name);
		System.out.println("age=" + age);
		raf.close();
	}
}


三、字符编码


1、概述:

(1)字符流的出现为了方便操作字符,更重要的是加入了编码的转换,即转换流。
(2)通过子类进行转换
(3)在两个对象进行构造时,可加入编码表
(4)可传入编码表的有:
         1)转换流:InuputStreamReader和OutputStreamWriter
         2)打印流:PrintStream和PrintWriter,只有输出流
(5)常见的编码表:
1)ASCII:美国标准信息交换码表。用一个字节的7位表示
2)IOS8859-1:拉丁码表;欧洲码表。用一个字节的8位表示
3)GB2312:中国的中文编码表
4)GBK:中国的中文编码表升级,融合了更多的中文文字字符。打头的是两个高位为1的两个字节编码。为负数
5)Unicode:国际标准码,融合了多种文字
6)UTF-8:最多用三个字节表示一个字符的编码表,包括:一位、两位、三位表示的字符
      UTF-8有自己的字节码:
      一个字节:0开头
      两个字节:字节一  ---> 110     位数:10 ~ 6
                          字节二  --->  10      位数:5 ~ 0
      三个字节:字节一  ---> 110     位数:15 ~ 12
                          字节二  --->  10      位数:11 ~ 6
                          字节三 --->  10       位数:5 ~ 0

2、编码和解码

 

(1)编码和解码:

1)编码:字符串变成字节数组
2)解码:字节数组变成字符串

(2)转换:

1)默认字符集:
      String  --->  byte[]   :srt.getBytes()
      byte[]   --->  String  :ne编码w String(byte[])

2)指定字符集:
      String  --->  byte[]   :srt.getBytes(charsetName)
      byte[]   --->  String  :new String(byte[],charsetName)

 

(3)对于编码和解码的字符集转换

1)如果编码失败,解码就没意义了。
2)如果编码成功,解码出来的是乱码,,则需对乱码通过再次编码(用解错码的编码表),然后再通过正确的编码表解码。针对于IOS8859-1是通用的。
3)如果用的是GBK编码,UTF-8解码,那么再通过2的方式,就不能成功了,因为UTF-8也支持中文,在UTF-8解的时候,会将对应的字节数改变,所以不会成功。




 

(4)特别注意:

对于中文的”联通“,这两个字比较特别,它的二进制位正好是和在UTF-8中两个字节打头的相同,可以找到对应的符号,但不再是”联通“了。

3、代码示例:

import java.util.*;

class EncodeDemo {
	public static void main(String[] args) throws Exception {
		CodeDemo();
		// 编译成功,解码失败后的解决方式
		CodeBack();
	}

	public static void CodeDemo() throws Exception {
		String s = "你好";
		byte[] b1 = s.getBytes();
		String s1 = new String(b1);
		System.out.println(Arrays.toString(b1));

		byte[] b2 = s.getBytes("GBK");// 默认编码
		String s2 = new String(b2);
		System.out.println("s1=" + s1 + ",s2=" + s2);
		System.out.println(Arrays.toString(b2));

		byte[] b3 = s.getBytes("UTF-8");// 国际编码
		String s3 = new String(b3);
		System.out.println("s3=" + s3);
		System.out.println(Arrays.toString(b3));

		byte[] b4 = s.getBytes("ISO8859-1");// 欧洲编码
		String s4 = new String(b4);
		System.out.println("s4=" + s4);
		System.out.println(Arrays.toString(b4));
	}

	// 编码与解码
	public static void CodeBack() throws Exception {
		String s = "你好";
		System.out.println("原数据:" + s);
		byte[] b1 = s.getBytes("GBK");// 默认编码
		System.out.println(Arrays.toString(b1));
		String s1 = new String(b1, "ISO8859-1");
		System.out.println("s1=" + s1);

		System.out.println("----对s1进行ISO8859-1编码-----");
		// 对s1进行ISO8859-1编码
		byte[] b2 = s1.getBytes("ISO8859-1");// 欧洲编码
		System.out.println(Arrays.toString(b2));

		String s2 = new String(b2, "GBK");
		System.out.println("s2=" + s2);
	}

}

/*output:
[-60, -29, -70, -61]
s1=你好,s2=你好
[-60, -29, -70, -61]
s3=浣犲ソ
[-28, -67, -96, -27, -91, -67]
s4=??
[63, 63]
原数据:你好
[-60, -29, -70, -61]
s1=????
----对s1进行ISO8859-1编码-----
[-60, -29, -70, -61]
s2=你好
*/

 

四、综合练习

五个学生,每个学生有3门课程的成绩,从键盘输入以上数据(姓名,三门课成绩),
输入格式:如:zahngsan,30,40,60计算出总成绩,并把学生的信息和计算出的总分数高低按顺序存放在磁盘文件stud.txt中

步骤:
1、描述学生对象
2、定义一个可操作学生对象的工具类

思路:
1、通过获取键盘录入一行的数据,并将该行数据的信息取出,封装成学生对象
2、因为学生对象很多,则需要存储,使用集合,因为要对学生总分排序
所以可以使用TreeSet
3、将集合中的信息写入到一个文件中

import java.io.*;
import java.util.*;

//定义学生类  
class Student implements Comparable<Student> {
	// 定义私有属性
	private String name;
	private int ma, cn, en;
	private int sum;

	// 构造Student函数,初始化
	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;
	}

	// 覆写compareTo方法,按学生总成绩排序
	public int compareTo(Student s) {
		int num = new Integer(this.sum).compareTo(new Integer(s.sum));
		if (num == 0)
			return this.name.compareTo(s.name);
		return num;
	}

	// 获取学生信息
	public String getName() {
		return name;
	}

	public int getSum() {
		return sum;
	}

	// 覆写hasdCode()和equals()方法,排除相同的两个学生
	public int hashCode() {
		return name.hashCode() + sum * 39;
	}

	public boolean equals(Object obj) {
		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() {
		return getStudents(null);
	}

	// 具备比较器的学生集合
	@SuppressWarnings("finally")
	public static Set<Student> getStudents(Comparator<Student> cmp) {
		BufferedReader bufr = null;
		Set<Student> stus = null;
		try {
			// 创建读取流对象缓冲区,键盘录入
			bufr = new BufferedReader(new InputStreamReader(System.in));
			String line = 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);
			}
		} catch (IOException e) {
			throw new RuntimeException("学生信息读取失败");
		}
		// 关闭流资源
		finally {
			try {
				if (bufr != null)
					bufr.close();
			} catch (IOException e) {
				throw new RuntimeException("读取流关闭失败");
			}
			return stus;
		}
	}

	// 将数据写入指定文件
	public static void write2File(Set<Student> stus, String fileName) {
		BufferedWriter bufw = null;
		try {
			// 创建写入流对象
			bufw = new BufferedWriter(new FileWriter(fileName));
			// 循环写入数据
			for (Student stu : stus) {
				bufw.write(stu.toString() + "\t");
				bufw.write(stu.getSum() + "");
				bufw.newLine();
				bufw.flush();
			}
		} catch (IOException e) {
			throw new RuntimeException("读取流关闭失败");
		}
		// 关闭流资源
		finally {
			try {
				if (bufw != null)
					bufw.close();
			} catch (IOException e) {
				throw new RuntimeException("写入流关闭失败");
			}
		}
	}
}

class Demo {
	public static void main(String[] args) {
		// 反转比较器,将成绩从大到小排
		Comparator<Student> cmp = Collections.reverseOrder();
		// 将录入的学生信息存入集合
		Set<Student> stus = StudentInfoTool.getStudents(cmp);
		// 将信息写入指定文件中
		StudentInfoTool.write2File(stus, "sudentinfo.txt");
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值