2020-09-09 Java_IO流(对象流,合并流)

对象流

		//对象序列化到文件
		public static void ObjectWrite(Object object,String FilePath) {
		//创建对象流
			ObjectOutputStream oos=null;
			try {
					oos=
				new ObjectOutputStream(new FileOutputStream(new File(FilePath)));
					//写进文件
					oos.writeObject(object);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				if (oos!=null) {
					try {
						oos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					
				}
			}
			
		}
		
		//反序列化文件
		public static HashMap<String, Object> ObjectReader(String FilePath){
			//创建对象
			ObjectInputStream ois=null;
			//创建接收集合
			HashMap<String, Object> hashList=null;
			try {
					ois=new ObjectInputStream(new FileInputStream(new File(FilePath)));

					try {
						//接受文件信息
						hashList=(HashMap<String, Object>)ois.readObject();
						
						if (hashList==null) {
							return null;	//没结果返回空
						}
						
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
					
			} catch (FileNotFoundException e) {
				
				e.printStackTrace();
			} catch (IOException e) {
				
				e.printStackTrace();
			}finally {
				try {
					
					if (ois!=null) 
						ois.close();
					
				} catcher (IOException e) {
					e.printStackTrace();
				}
			}
			return hashList;
		}

对象流实现需要将实体类进行序列化,实体类序列化需要实现Serializable接口。

如果实体类没有实现序列化接口会报NotSerializableException的异常。

实体类中如果有个成员变量是另一个实体类,那么那个实体类也需要实现Serializable接口。

合并流

将多个流合并成一个流进行读写

核心代码

			//两个流合并
			SequenceInputStream sis=new SequenceInputStream(inputStream, inputStream);

			//多个流合并
			//创建集合存储流
			LinkedHashSet<InputStream> linkedHashSet=new LinkedHashSet<>();
			
			//转换迭代器
			Iterator<InputStream> itr=linkedHashSet.iterator();
			
			SequenceInputStream sis=new SequenceInputStream(new Enumeration<InputStream>() {
				//匿名内部类
				@Override
				public boolean hasMoreElements() {
					// 能否查到下一个元素
					return itr.hasNext();
				}

				@Override
				public InputStream nextElement() {
					// 返回下一个元素
					return itr.next();
				}
			});

猜你喜欢

转载自blog.csdn.net/weixin_44158992/article/details/108493454