黑马程序员_JAVA_IO(三)

------ Java培训、Android培训、iOS培训、.Net培训 、期待与您交流! -------


一、对象序列化        

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

常用到的两个类:ObjectInputStream和ObjectOutputStream。
被操作的对象需要实现Serializable接口(也称标记接口)
 
关于Serializable接口:
        1、接口Serializable中没有方法,称之为标记接口
        2、序列化运行时使用一个称为 serialVersionUID的版本号与每个可序列化类相关联,用于验证序列化对象的发送者和接收者是否为同一对象。如果接收者加载的该对象的类的 serialVersionUID与对应的发送者的类的版本号不同,则反序列化将会导致 InvalidClassException。
             public static final long serialVersionUID = 42L;

注意:1、静态成员不能被序列化,因为静态在方法区,序列化只能对堆内的对象进行序列化。

             2、非静态成员要不被序列化,可以用关键字transient修饰,保证非静态成员保存在堆内存中,不能存入文件中。

import java.io.*;
class Peason implements Serializable {
	// 自定义serialVersionUID版本号
	public final static long serialVersionUID = 32L;

	private String name;
	transient int age;// 使用transient关键字表示该成员不被序列化
	static String country = "CN";// 静态成员不能序列化

	// 构造函数
	Peason(String name, int age) {
		this.name = name;
		this.age = age;
	}

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

// 序列化测试类
class ObjectStreamDemo {
	public static void main(String[] args) {
		// 指定文件
		File file = new File("obj.txt");
		Peason p = new Peason("zhangsan", 25);

		// 序列化指定对象
		writeObj(p, file);
		// 反序列化
		readObj(file);
	}

	// 将指定对象序列化到指定文件中
	public static void writeObj(Peason p, File file) {
		ObjectOutputStream oos = null;
		try {
			// 创建写入流对象,关流文件
			oos = new ObjectOutputStream(new FileOutputStream(file));
			oos.writeObject(p);// 写入对象数据
		} catch (IOException e) {
			throw new RuntimeException("对象写入失败");
		} finally {
			try {
				if (oos != null)
					oos.close();
			} catch (IOException e) {
				throw new RuntimeException("关流失败");
			}
		}
	}

	// 读取指定文件中的对象,也称反序列化
	public static void readObj(File file) {
		ObjectInputStream ois = null;
		try {
			// 创建读取流对象,关联文件
			ois = new ObjectInputStream(new FileInputStream(file));
			// 读取文件中的对象
			Peason p = (Peason) 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("关流失败");
			}
		}
	}
}


二、管道流( PipedInputStream和PipedOutputStream )
特点:
         1、输入输出可以直接进行连接,不用再借助数组或集合等容器进行临时存储。     
         2、一般结合多线程使用。通常,数据由某个线程写入PipedOutputStream对象,并由其他线程从连接的 PipedInputStream 读取。
 
操作步骤:
        1、要先创建一个读和写的两个类,实现Runnable接口,因为是两个不同的线程,覆盖run方法,注意,需要在内部处理异常。
        2、创建两个管道流,并用connect()方法将两个流连接
        3、创建读写对象,并传入两个线程内,并start执行。
import java.io.*;
class PipedStreamDemo {
	public static void main(String[] args) {
		try {
			// 创建管道流对象,并关联
			PipedInputStream in = new PipedInputStream();
			PipedOutputStream out = new PipedOutputStream();
			in.connect(out);

			// 启动线程
			new Thread(new Read(in)).start();
			new Thread(new Write(out)).start();
		} catch (IOException e) {
			throw new RuntimeException("管道流关联失败");
		}
	}
}

// 读取线程
class Read implements Runnable {
	private PipedInputStream in;

	Read(PipedInputStream in) {
		this.in = in;
	}

	// 覆盖run方法
	public void run() {
		try {
			// 用来存储读到的字节
			byte[] by = new byte[1024];
			System.out.println("读取前。。没有数据阻塞");
			// 读取流中数据
			int len = in.read(by);
			System.out.println("读到数据。。阻塞结束");

			// 将字节数组转换为字符串打印输出
			String s = new String(by, 0, len);

			System.out.println(s);
		} catch (IOException e) {
			throw new RuntimeException("读取数据失败");
		} finally {
			try {
				if (in != null)
					in.close();
			} catch (IOException e) {
				throw new RuntimeException("流关闭失败");
			}
		}
	}
}

// 写线程
class Write implements Runnable {
	private PipedOutputStream out;

	Write(PipedOutputStream out) {
		this.out = out;
	}

	// 覆盖run方法
	public void run() {
		try {
			System.out.println("开始写入数据,等待3秒后。");
			Thread.sleep(3000);
			// 写入数据到管道流中
			out.write("piped shi shem ma?".getBytes());
		} catch (Exception e) {
			throw new RuntimeException("写入数据失败");
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (IOException e) {
				throw new RuntimeException("流关闭失败");
			}
		}
	}
}


三、RandomAccessFile

        1RandomAccessFile此类的实例支持对随机访问文件的读取和写入,自身具备读写方法。

        2、该类不算是IO体系中的子类,而是直接继承Object,但是它是IO包成员,因为它具备读写功能,内部封装了一个数组,且通过getFilePointer方法获取指针位置,来对数组的元素进行操作,同时可通过seek方法改变指针的位置。

        3、可以完成读写的原理:内部封装了字节输入流和输出流。

        4、构造函数:RandomAccessFile(File file,String mode)


注意:1、如果模式为只读r,则不会创建文件,会去读一个已存在的文件,若文件不存在,则会出现异常。

    2、如果模式为读写rw,且该对象的构造函数要操作的文件不存在,会自动创建;如果存在,则不会覆盖。

 

特有方法:

        1seek(long pos)//调整对象中指针。来进行指定位置的数据读取和写入。数据要有规律。如果设置的指针位置已有数据,写入时将会将其修改。用seek可以表示随机读写访问。

        2int skipBytes(int n):跳过指定字节数,不可往前跳

 RandomAccessFile中也有对基本数据类型进行读写的方法。还有readLine方法。

//需求:使用RandomAccessFileDemo进行读写操作
import java.io.*;
public class RandomAccessFileDemo {
	public static void main(String[] args) throws IOException {
		// 指定文件
		File file = new File("1.txt");
		// 写数据
		writeFile(file);
		// 读数据
		readFile(file);
	}

	// 读取指定文件中的数据
	public static void readFile(File file) throws IOException {
		// 创建对象
		RandomAccessFile raf = new RandomAccessFile(file, "r");
		// 设置指针位置
		raf.seek(4);

		// 设置跳过的字节数
		// raf.skipBytes(8);

		// 读取四个字节存入
		byte[] by = new byte[4];
		// 读数据
		raf.read(by);
		// 将存入数据的字节数组转换为字符串
		String str = new String(by);
		raf.close();// 关流
		System.out.println("str=" + str);
	}

	// 将数据写入指定文件中
	public static void writeFile(File file) throws IOException {
		// 创建对象
		RandomAccessFile raf = new RandomAccessFile(file, "rw");
		raf.write("abcdefghigk".getBytes());
		raf.close();// 关流
	}
}


四、操作基本数据类型的流对象( DataStream )

        1、操作基本数据类型的流对象:DataInputStreamDataOutputStream

        2、这两个读写对象,可用于操作基本数据类型的流对象,包含读写各种基本数据类型的方法。

 

String readUTF();//对应writeUTF,读取以UTF-8修改版编码写入的字符串

writeUTF(String str);//以与机器无关方式使用UTF-8修改版编码将一个字符串写入基础输出流。


五、操作数组与字符串的流

        1ByteArrayInputStream:在构造函数的时候,需要接受数据源,而且数据源是一个字节数据。

        2ByteArrayOutputStream:在构造函数的时候,不用定义数据目的,因为该对象中已经在内部封装了可变长度的字节数组,这就是数据的目的地。


ByteArrayOutputStream特有方法

        writeTo(OutputStream out);//将此 byte 数组输出流的全部内容写入到指定的输出流参数中

        int size();//当前缓冲区的大小

        String toString();//使用平台默认的字符集,通过解码字节将缓冲区内容转换为字符串


 注意:1、这个对象并没有调用底层资源,所以不用关闭流资源,即使关闭后,仍可调用。 

     2、内部包含缓冲区,相当于以内存作为流操作源和目的,不会产生任何IO异常。 

     3、因为writeTo(OutputStream out)这个方法用到了字节输出流,需要抛IO异常,也是字节数组流中唯一需要抛异常的方法。

对应的字符数组和字符串

        字符数组流:CharArrayReaderCharArrayWriter

        字符串流:   StringReaderStringWriter

//使用IO中操作字节数组的流对象读写数据
import java.io.*;
class ByteArrayStreamDemo {
	public static void main(String[] args) {
		// 创建一个byte数组输入流,数据源
		ByteArrayInputStream bais = new ByteArrayInputStream(
				"ABCDEFG".getBytes());

		// 创建一个新的byte数组输出流,数据目的
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		int by = 0;
		while ((by = bais.read()) != -1) {
			// 写入数据
			baos.write(by);
		}

		// 输出数据长度
		System.out.println(baos.size());

		// 以字符串输出数据
		System.out.println(baos.toString());

		try {
			// 调用此方法时,需要抛出异常
			baos.writeTo(new FileOutputStream("writeTo.txt"));
		} catch (IOException e) {
			throw new RuntimeException("数据写入文件失败");
		}
	}
}

六、字符编码

1、字符流的出现为了方便操作字符。

2、更重要的是加入了编码的转换,即转换流。

3、通过子类转换流来完成。在两个对象进行构造的时候,可以加入字符集(即编码表),可传入编码表的有:

        1、转换流:InuputStreamReaderOutputStreamWriter

        2、打印流:PrintStreamPrintWriter,只有输出流

常见的编码表:

        1ASCII:美国标准信息交换码表。用一个字节的7位表示

        2IOS8859-1:拉丁码表;欧洲码表。用一个字节的8位表示

        3GB2312:中国的中文编码表()早期

        4GBK:中国的中文编码表升级,融合了更多的中文文字字符。打头的是两个高位为1的两个字节编码。为负数

        5Unicode:国际标准码,融合了多种文字。所有文字都用两个字节来表示,Java语言使用的就是unicode

        6UTF-8:最多用三个字节表示一个字符的编码表,根据字符所占内存空间不同,分别用一个、两个、三个字节来编码。


注意: 1、如果编码失败,解码就没意义了。

              2、如果编码成功,解码出来的是乱码,则需对乱码通过再次编码(用解错码的编码表),然后再通过正确的编码表解码。针对于IOS8859-1是通用的。

              3、如果用的是GBK编码,UTF-8解码,此时通过再次编码后解码的方式,就不能成功了,因为UTF-8也支持中文,在UTF-8解的时候,会将对应的字节数改变,所以不会成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值