Java IO辅助概念(内存流)

针对内存流,java.io包里面提供了两组操作:

·字节内存流:ByteArrayInputStream,ByteArrayOutputStream;

·字符内存流:CharArrayReader,CharArrayWriter

名称

ByteArrayInputStream

ByteArrayOutputStreamWriter

继承结构

java.lang.Object

    |-java.io.InputStream

       |-java.io.ByteArrayInputStream

java.lang.Object

    |-java.io.OutputStream

       |-java.io.ByteArrayOutputStream

构造方法

public ByteArrayInputStream(byte[ ] buf)

public ByteArrayOutputStream()

表示将要操作的数据设置到输入流

从内存输出数据

为了更好说明问题,特别举一个例子:

·以文件操作为例:

    |-输出(OutputStream):程序→OutputStream→文件;

    |-输入(InputStream):程序←InputStream←文件;

·以内存操作为例:

    |-输出(InputStream):程序→InputStream→内存;

    |-输入(OutputStream):程序←OutputStream←内存;

·为了方便实现字母大小写的转换可用Charactor:

    |-public static char toLowerCase(char ch);

    |-public static int toLowCase(int codePoint)

    |-public static char toUpperCase(char ch)

    |-public static int toUpperCase(int codePoint)

范例1:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Demo {
	public static void main(String[] args) throws Exception {// 此处直接抛出错误
		String str = "i am your father";// 要被转换的字符串
		// 本次通过内存流操作实现转换,先将数据保存到内存流当中,然后从中取出每一个数据,
		// 将所有要读取的数据设置到内存输入流之中,利用向上转型
		InputStream in = new ByteArrayInputStream(str.getBytes());
		// 为了能够将所有内存流数据取出,可以使用ByteArrayOutputStream
		OutputStream out = new ByteArrayOutputStream();
		int temp = 0;// 每次读取一个字节
		// 此次循环之后,所有数据都保存在内存输出流对象之中。
		while ((temp = in.read()) != -1) {// 每次读取一个数据
			out.write(Character.toUpperCase(temp));// 字节输出流
		}
		System.out.println(out);
		in.close();
		out.close();
	}

}

============分割线============

范例2:实现文件合并输出

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class Demo {
	public static void main(String[] args) throws Exception {// 此处直接抛出错误
		File fileA = new File("e:" + File.separator + "yummy.txt");
		File fileB = new File("e:" + File.separator + "what.txt");
		InputStream inA = new FileInputStream(fileA);
		InputStream inB = new FileInputStream(fileB);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int temp = 0;
		while ((temp = inA.read()) != -1) {
			out.write(temp);
		}
		while ((temp = inB.read()) != -1) {
			out.write(temp);
		}
		byte[] data = out.toByteArray();
		inA.close();
		inB.close();
		System.out.println(new String(data));
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值