IO流的分析

本文深入探讨了Java中字节流和字符流的区别与使用场景,指出在处理文本时应使用字符流以避免编码问题。通过示例代码展示了如何使用字节流和字符流进行文件读写,以及ObjectOutputStream和ObjectInputStream进行对象序列化。同时,提到了Properties类读取字节流并获取键值对内容的方法,并展示了如何改变System.out的输出目的地。
摘要由CSDN通过智能技术生成

字符流和字节流

  • 拷贝东西可以用字节流,但读取文本就要用字符流。因为中文和英文的所占字节不同,一个文本中可能包含中英混合,如果用字节流读取文本,会发生读取字节分离(在读取文本的时候是读取到一个byte数组里,但byte数组有一定大小,不能一下子读完,可能出现一个中文字符读取了一半。导致部份乱码),如果不牵涉到读取文本啥的可以用字节流。字节流可以读取任何文件。
  • 关于拷贝和读取的时候,可以借byte数组来当缓冲。java中的String类可以用byte组数创建新的string对象,如图所示
FileInputStream files=null;
        try {
        	 byte[] a=new byte[5];
			 files=new FileInputStream("src/com/ht/io/temple");
			 char onebyte=(char) files.read();
			 System.out.print(onebyte);
			 int readcount;
			 while((readcount=files.read(a))!=-1) {
				 System.out.print(new String(a,0,readcount));
			 }
  • 字符流借用char数组当缓冲
FileReader reader=null;
        try {
        	 char[] a=new char[4];
			 reader=new FileReader("..\\temple");
			 int readcount;
			 while((readcount=reader.read(a))!=-1) {
				 System.out.print(new String(a,0,readcount));
			 }
		} catch (FileNotFoundException e) {

-ObjectOutputStream和ObjectInputStream可以序列化对象,但对象要实现Serializable接口

SerializeTest.Student a=new SerializeTest.Student("zhangsan");
		ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("serialize"));
		out.writeObject(a);
		out.flush();
		out.close();
  • 关于util下的Properties类,该类继承了hashtable,properties对象可以加载字节流对象,从而获取流中的内容。通过键值对的方式获取。
FileInputStream a=new FileInputStream("useinf");
		Properties c=new Properties();
		c.load(a);
	
		System.out.println(c.get("username")+"\n"+c.get("password"));
  • System.out.其中out是个printstream的对象,如果需要设置输出流输出到哪里可以进行设置,通过System.setout()方法
//1.先定义输出文件流的位置:new FileOutputStream("log")
		//2.通过new FileOutputStream("log")作为构造函数的参数 
            PrintStream c=new PrintStream(new FileOutputStream("log"));
            //3设置输出流对象,setOut()方法可以改变输出流
            System.setOut(c);
            //4以后的输出不会在控制台显示,会把输出写到log文件中
            System.out.println("hello PrintStream");
          //5System.out是调用了System类的静态数据成员out
           PrintStream out=new PrintStream(new FileOutputStream(FileDescriptor.out));
           System.setOut(out);
           System.out.println("你好syste.out");
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值