随机访问流and合并流and序列化流andPropertoes

本文通过多个示例展示了 Java 中 IO 流的应用,包括使用 RandomAccessFile 实现多线程下载文件的随机访问,利用 SequenceInputStream 合并两个字节数组为一个字符串,演示如何使用 ObjectOutputStream 和 ObjectInputStream 进行对象的序列化和反序列化,以及展示 Properties 类与 IO 操作的结合使用。
class RandomAccessTest 
{	// 多线程 下载文件  随机访问流
	public static void main(String[] args) 
	{
		RandomAccessFile f = null;
	try{
										// String name,String mode 模式(读写)
		f =new RandomAccessFile("D:\\xx.txt","rw");
		long pointer =f.getFilePointer();
		f.write("牧佑叔叔_");
		pointer +=",牧佑叔叔".getBytes();
		f.seek(pointer - "叔叔".getBytes.length);
		f.seek(1);//操作指针。从哪开始插数据0,1,2,3字节 
		// 所以转换
		//	f.seek("牧".getBytes().length());
	
		f.wirte("么么哒");
	}catch(IOException e){
		
	} finally{
		if(f !=null){
			try{
		f.close();
			}catch(IOException ex){}
		}
	}

	}
}



class SequenceInputStream 
{
	//  合并流。将两个文件合并到一个文件
	public static void main(String[] args) thorws IoException
	{
		//String流
		ByteArrayInputStream bis = new ByteArrayInputStream("牧佑".getBytes());
		ByteArrayInputStream bis2 = new ByteArrayInputStream("叔叔".getBytes());
		
		SequenceInputStream sis = new SequenceInputStream(bis,bis2);
		StringBuilder sb = new StringBuilder();
		//放到byte数组里面
		byte[] buf = new byte[1024];
		int len = -1;
		while((len =sis.reder(buf))!= -1){
			byte[] tm = new byte[len];
			//System.arraycopy(buf,0,tm,0,len);
		sb.append(new String(buf,0,len));
		}
		System.out.println(sb.toString());

	}
}







class ObjectOutputStream and ObjectInputStream 
{
	// 序列化流 操作对象流化  
	public static void main(String[] args)  throws FileNotFoundException
	{
		FileOutputStream fos = new FileOutputStream("D:\\xx.txt");
		// 对象必须继承序列化接口
		//如果对象字段不需要 系列化 使用 transient声明即可
		// private transient String name;
		Student s = new Student();
		s.setMomo("腹股沟");
		s.setAff("好像傻");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writerObject(s);
		oos.flush();
		oos.close();
		FileInputStream f = new FileInputStream("D:\\xx.txt");
		ObjectInputStream i = new ObjectInputStream(f);
		Student sfg = (Student)i.readObject();
		System.err.println(sfg.getMomo);
		i.close();
	}
}






class PropertiesDemo 
{
	// Propertoes 与 IO 结合
	public static void main(String[] args)  throws IOException
	{
		Reader r = new Reader("D:\\xt.properties");
		// 新IO 可以用paths
		Path path = Paths.get("d:","pro","sd.txt");
		Properties pro = new Properties();
		pro.load(r);
		pro.close();
		Enumeration<String>name = (Enumeration<String>)pro.propertyName();
		while(name.hasMoreElements){
		String key = name.nextElements()'
		Sytem.out.println("key:"+key);
		System.out.println("values:"+pro.getProperty(key));
		
		//读
		Writer e = new FileWriter("D:\\xt.properties");
		pro.setProperty("student","牧佑");
		pro.store(e,"新增");
		e.close();
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值