黑马程序员--java复习之IO包中其他类

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


在前面两天中学习了IO流,主要是字符流和字节流。内容包括字符流的几个类 Reader和Writer,文件操作类 FileReader、FileWriter、字符流缓冲区 BufferedReader和BufferedWriter,转换流 BufferedInputStreamReader和 BufferedOutputStreamWriter,字节流的InputStream和OutputStream,文件操作类 FileInputStream和FileOutputStream,字节流缓冲区  BufferedInputStream和BufferedOutputStream。这几个类之间的关系图如下:




下面,我们来的看一下IO包中的其他类

一、操作对象的流(ObjectInputStream和ObjectOutputStream)

ObjectInputStream和ObjectOutputStream:可以直接操作对象的流(对象的序列化)

又称为对象的序列化,或者对象的持久化。在我们的程序运行结束以后,我们在程序中创建的对象也会随着程序的结束而结束。现在我们可以将对象作一个持久化,即将以文件的形式保存在硬盘上。这里就要用到操作对象的流  ObjectInputStream 和 ObjectOutputStream

ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream。通过在流中使用文件可以实现对象的持久存储。
主要方法:writeObject()
ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化。
主要方法:readObject()
上面这两个类的父类分别是OutputStream和InputStream,所以继承了这两个类的方法

通过代码来看看其应用:
import java.io.*;
class ObjectStreamDemo
{
	public static void main(String[] args)
	{
		//writeObject();
		readObject();
	}
	
	//从文件中读取对象(反序列化)
	public static void readObject()
	{
		ObjectInputStream ois=null;
		try
		{
			//将对象反序列化
			ois =new ObjectInputStream(new FileInputStream("obj.txt"));
			//读取对象
			Person p=(Person)ois.readObject();
			
			System.out.println(p);
		}
		catch(Exception e)
		{
			System.out.println(e.toString());
		}
		finally
		{
			try
			{
				if(ois!=null)
					ois.close();
			}
			catch(IOException e)
			{
				System.out.println(e.toString());
			}
		}
	}
	
	//将对象序列化(将对象持久化,即将对象存储在文件中)
	public static void writeObject()
	{
		ObjectOutputStream oos=null;
		try
		{
			oos=new ObjectOutputStream(new FileOutputStream("obj.txt"));
				//将对象序列化
			oos.writeObject(new Person("zhangsan0",30));
			//也可以序列化多个对象,这样在读取的时候是依次读取的
			//oos.writeObject(new Person("zhangsan",30));
			//oos.writeObject(new Person("zhangsan",30));
			//oos.writeObject(new Person("zhangsan",30));
		}
		catch(IOException e)
		{
			System.out.println(e.toString());
		}
		finally
		{
			try{
				if(oos!=null)
					oos.close();
			}
			catch(IOException e)
			{
				System.out.println(e.toString());
			}
		}

	}
}

person类:被序列化的对象所属类要实现Serializable接口
每个类都有自己的UID,当我们将被序列化的对象所属类修改后,这个UID就会改变,为避免类修改以后,以前保存的对象无法反序列化,所以自定义了UID,如下:
import java.io.*;
class Person implements  Serializable
{
	//自定义UID变量,这样,即使类变化了,UID依然不变,以前序列化的对象依然可以读取
	public static final log serialVersionUID=42L;
	private String name;  
	private int age; //如果变量不想序列化,可以在前面加修饰符:transient
	public int getAge()
	{
		return age;
	}
	public void setAge(int age)
	{
		this.age=age;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name=name;
	}
	Person(String name,int age)
	{
		this.name=name;
		this.age=age;
	}
	public String toString()
	{
		return name+"::"+age;
	}
}

对象在文件中:

当我们对对象反序列化后:




二、管道流

PipedInputStream 和 PipedOutputStream

输入输出可以直接进行连接,通过结合线程使用.


1、管道输入流应该连接到管道输出流;
2、管道输入流提供要写入管道输出流的所有数据字节。
通常,数据由某个线程从 PipedInputStream 对象读取,并由其他线程将其写入到相应的 PipedOutputStream。
不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。
3、管道输入流包含一个缓冲区,可在缓冲区限定的范围内将读操作和写操作分离开。
如果向连接管道输出流提供数据字节的线程不再存在,则认为该管道已损坏。 


1、可以将管道输出流连接到管道输入流来创建通信管道。管道输出流是管道的发送端。
2、通常,数据由某个线程写入 PipedOutputStream 对象,并由其他线程从连接的 PipedInputStream 读取。



代码:
import java.io.*;
class PipedStreamDemo
{
	public static void main(String[] args) throws IOException
	{
		//创建管道输入流对象
		PipedInputStream pis=new PipedInputStream();
		//创建管道输出流对象
		PipedOutputStream pos=new PipedOutputStream();
		//管道输入流输出流连接
		pis.connect(pos);
		
		Write write=new Write(pos);
		Read read=new Read(pis);
		
		
		new Thread(write).start();
		new Thread(read).start();
	}
	
}

//自定义类实现Runnable接口
class Write implements Runnable
{
	private PipedOutputStream pos;
	Write(PipedOutputStream pos)
	{
		this.pos=pos;
	}
	
	public void run()
	{
		try
		{
			System.out.println("开始写入数据,等待6秒后。。。");
			Thread.sleep(6000);
			//管道输出流写入数据,是管道的发送端
			pos.write("我来了".getBytes());
			pos.close();
		}
		catch(Exception e)
		{
			throw new RuntimeException("管道流输出失败!");
		}
	}
}
//自定义类实现Runnable接口
class Read implements Runnable
{
	private PipedInputStream pis;
	Read(PipedInputStream pis)
	{
		this.pis=pis;
	}
	
	public void run()
	{
		try
		{
			byte[] byt=new byte[1024];
			System.out.println("读取前。。。没有数据,阻塞中。。。。");
			//管道输入流读取数据
			int len=pis.read(byt);
			System.out.println("读到数据。。。。阻塞结束");
			String s=new String(byt,0,len);
			System.out.println(s);
			pis.close();
		}
		catch(Exception e)
		{
			throw new RuntimeException("管道流输入失败!");
		}
	}
}

结果:



三,随机访问文件类(RandomAccessFile)

随机访问文件,自身具备读写的方法,通过skipBytes(int x),seek(int x) 来达到随机访问


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


其实完成读写的原理就是内部封装了字节输入流和输出流。

通过构造函数可以看出,该类只能操作文件。而且操作文件还有模式:只读r,读写rw。如果模式为只读r,不会创建文件,会去读取一个已存在的文件,如果该文件不存在,则会出现异常。如果模式为rw,操作的文件不存在,会自动创建,如果存在不会覆盖。

代码:
import java.io.*;
class RandomAccessFileDemo
{
	public static void main(String[] args)
	{
		//writeFile();
		read();
	}
	
	//在指定位置插入
	public static void write_2()
	{
		RandomAccessFile raf=null;
		try
		{
			//创建一个随机访问文件类的对象
			raf=new RandomAccessFile("ran.txt","rw");
			
			//指定指针的位置
			ran.seek(8*1);
			//在指针位置插入
			raf.write("周七".getBytes());
			raf.writeInt(105);
			
		}
		catch(IOException e)
		{
			System.out.println(e.toString());
		}
		finally
		{
			try{
				if(raf!=null)
					raf.close();
			}
		}
	}
	
	//取值
	public static void read()
	{
		RandomAccessFile raf=null;
		try
		{
			raf=new RandomAccessFile("ran.txt","r");// 此处只是读取,所以模式为r
			
			//调整对象中的指针
			//raf.seek(8);
			
			//跳过指定的字节数(只能往后跳,不能往前跳)
			raf.skipBytes(8);
			
			byte[] byt=new byte[4];
			//读取
			raf.read(byt);
			String name=new String(byt);
			
			int age=raf.readInt();
			System.out.println("name="+name);
			System.out.println("age="+age);
			
		}
		catch(IOException e)
		{
			System.out.println(e.toString());
		}
		finally
		{
			try
			{
				if(raf!=null)
					raf.close();
			}
			catch(IOException e)
			{
				System.out.println(e.toString());
			}
		}
	}
	
	//使用RandomAccessFile的写入功能
	public static void writeFile()
	{
		RandomAccessFile raf=null;
		try
		{
			raf=new RandomAccessFile("ran.txt","rw"); //模式为读写模式
			
			raf.write("李四".getBytes());
			raf.writeInt(97);
			
			raf.write("张三".getBytes());
			raf.writeInt(99);
		}
		catch(IOException e)
		{
		     System.out.println(e.toString());	
		}
		finally
		{
			try{
				if(raf!=null)
					raf.close();
			}
			catch(IOException e)
			{
				System.out.println(e.toString());
			}
		}
		
	}
}



四、操作基本数据类型(DataInputStream和DataOutputStream)

构造方法
DataInputStream(InputStream in)   使用指定的底层 InputStream 创建一个 DataInputStream。

import java.io.*;
class DataStreamDemo
{
	public static void main(String[] args)
	{
		//writeData();
		//readData();
		//writeUTFDemo();
		readUTFDemo();
	}
	
	//读取UTF-8修订版编码的数据
	public static void readUTFDemo()
	{
		DataInputStream dis=null;
		try
		{
			dis=new DataInputStream(new FileInputStream("utf.txt"));
			
			String s=dis.readUTF();
			
			System.out.println(s);
		}
		catch(IOException e)
		{
			throw new RuntimeException("读取失败");
		}
		finally
		{
			try{
				if(dis!=null)
					dis.close();
			}
			catch(IOException e)
			{
				throw new RuntimeException("读取失败");
			}
		}
	}
	
	//使用的是UTF-8修订版将数据写入数据(UTF-8修订版每个汉字占4个字节)
	//使用UTF-8修订版写入的数据也必须要用UTF-8修订版来读取
	public static void writeUTFDemo() 
	{
		DataOutputStream dos=null;
		try
		{
			dos=new DataOutputStream(new FileOutputStream("utf.txt"));
			dos.writeUTF("你好"); //使用的是UTF-8修订版
			
		}
		catch(IOException e)
		{
			System.out.println(e.toString());
		}
		finally
		{
			try
			{
				if(dos!=null)
					dos.close();
			}
			catch(IOException e)
			{
				throw new RuntimeException("写入失败!");
			}
		}
		
	}
	
	//读取
	public static void readData()
	{
		DataInputStream dis=null;
		try
		{
			//读取流对象
			dis=new DataInputStream(new FileInputStream("data.txt"));
			int i=dis.readInt();//读取Int类型
			boolean b=dis.readBoolean();
			double d=dis.readDouble();
			
			System.out.println("int="+i+",boolean="+b+",double="+d);
		}
		catch(IOException e)
		{
			System.out.println(e.toString());
		}
		finally
		{
			try{
				if(dis!=null)
					dis.close();
			}
			catch(IOException e)
			{
				System.out.println(e.toString());
			}
		}
	
	}
	
	//写入数据
	public static void writeData()
	{
		DataOutputStream dos=null;
		try
		{
			//创建基本数据类型操作类的对象
			dos=new DataOutputStream(new FileOutputStream("data.txt "));	
			dos.writeInt(234);//写入Int类型(与OutputStream的write区别在于,write是将int类型的最后八位写进去,而这里是写入32位)
			dos.writeBoolean(true);
			dos.writeDouble(955.355);
		}
		catch(IOException e)
		{
			System.out.println(e.toString());
		}
		finally
		{
			try{
				if(dos!=null)
					dos.close();
			}
			catch(IOException e)
			{
				System.out.println(e.toString());
			}
		}
	}
}


五、对数组进行操作的流对象

用于操作字节数组的流对象


ByteArrayInputStream:在构造的时候,需要接收数据源,而且数据源是一个字节数组。
构造函数:ByteArrayInputStream(byte[] buf) 
ByteArrayInputStream(byte[] buf, int offset, int length)

ByteArrayOutputStream:在构造的时候,不用定义数据目的,因为该对象中已经内部封装了可变长度的字节数组。
这就是数据目的地。因为这两个流对象都是操作的数组,并没有使用系统资源。所以,不用进行close关闭。 

在流操作规律讲解时:
源设备:键盘  System.in, 硬盘  FileStream  内存  ArrayStream
目的设备:
控制台:System.out 硬盘 FileStream  内存 ArrayStream

用流的读写思想来操作数组


还有其他的:
CharArrayReader 和 CharArrayWriter  操作字符数组的流对象,同理,CharArrayReader的源是一个字符数组 char[] ,CharArrayWriter  内部封装有一个字符数组

StringReader 和 StringWriter 操作字符串的流对象  StringReader 的源是一个字符串



代码(演示ByteArrayOutputStream)

import java.io.*;

class ByteArrayStream
{
	public static void main(String[] args)	
	{
		//数据源(数据源是一个字节数组)
		ByteArrayInputStream bis=new ByteArrayInputStream("呵呵".getBytes());
		
		//数据目的
		ByteArrayOutputStream bos=new ByteArrayOutputStream();
		
		int len=0;
		while((len=bis.read())!=-1)
		{
			bos.write(len);
		}
		
		System.out.println(bos.toString());
		
		
		//writeTo(OutputStream os)
		//同样可以将一个OutputStream作为目的
		bos.writeTo(new FileOutputStream("test.txt"));
		
	}
}


六、字符编码

A、字符流的出现是为了方便操作字符
B、更重要的是加了编码转换。
C、通过子类转换流来完成
InputStreamReader
OutputStreamWriter
D、在两个对象进行构造的时候可以加入字符集



编码表的由来:
1、计算机只能识别二进制数据,早期由来是电信号
2、为了方便应用计算机,让它可以识别各个国家的文字。
3、就将各个国家的文字用数字来表示,并一一对应,形成一张表,即编码表。



编码:字符串变成字节数组
String-->byte[]:  str.getBytes(charsetName);


解码:字节数组变成字符串
byte[]-->String: new String(byte[],charsetName );


用什么编码格式编的码,就用相应的格式解码。如,用UTF-8编码,就得用UTF-8解码

如:
import java.util.*;
import java.io.*;
class EncodeDemo
{
	public static void main(String[] args) throws Exception
	{				
		writeText() ;
		readText();
		
	}
	
	//解码:字节数组变成字符串
	public static void readText()
	{
		InputStreamReader isr=null;
		try
		{
			isr=new InputStreamReader(new FileInputStream("utf.txt"),"utf-8");
			
			char[] buf=new char[1024];
			int len=0;
			while((len=isr.read(buf))!=-1)
			{
				String s=new String(buf,0,len);
				System.out.println(s);
			}
		}
		catch(IOException e)
		{
			System.out.println(e.toString());
		}
		finally
		{
			try{
				if(isr!=null)
					isr.close();
			}
			catch(IOException e)
			{
				System.out.println(e.toString());
			}
		}
	}
	public static void writeText() throws IOException
	{
		//使用UTF-8格式编码。(只能用UTF-8来解码)
		OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("utf.txt"),"utf-8");
		osw.write("你好");
		osw.close();
	}
}

结果:

如果编码的时候使用UFT-8,解码的时候使用GBK,结果:  可以看出,两个结果完全不同,这是因为当我们解码的时候,将字节拿到GBK编码表中查表的时候,出来的就是上图中的几个字符。


再看另一个例子:
import java.util.*;
import java.io.*;
class EncodeDemo
{
	public static void main(String[] args) throws Exception
	{
		
		String s="你好";
		
		byte[] b1=s.getBytes(); //编码:字符串变成字节数组(默认是GBK)
		
		System.out.println(Arrays.toString(b1));
		String s1=new String(b1,"ISO8859-1");  //解码:字节数组变成字符串
		System.out.println(s1);//解码后的字符串
		
		//对s1进行ISO8859-1编码
		byte[] b2=s1.getBytes("ISO8859-1");
		System.out.println(Arrays.toString(b2));
		
		String s2=new String(b2,"gbk"); //再用GBK解码
		System.out.println(s2);		
		
	}
	
	
}

结果:

其编码解码过程如图:


好了,IO包中的其他类就到这里了


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值