Java字节输入流2

      昨天晚上研究了一点Java的字节输入流,但输出的都是一个个的数字,那怎么把其输出为原来的样子呢?今天试了一下,如下面的代码。

 

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class inputStreamTest 
{
	public static void main(String[] args)
	{		
		byteArrayInputStream();
		
		fileInputStreamTest();
	}
	
	public static void byteArrayInputStream()
	{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try 
		{
			out.write("abc123中国456def".getBytes());
			byte[] buffer = out.toByteArray();
			out.close();
			
			ByteArrayInputStream in = new ByteArrayInputStream(buffer);
			byte[] buff = new byte[in.available()];
			in.read(buff);
			in.close();
			
			System.out.println(new String(buff, "UTF-8")); //输出结果为:abc123?й?456def
			System.out.println(new String(buff, "GB2312")); //输出结果为:abc123中国456def
			System.out.println(new String(buff, "GBK")); //输出结果为:abc123中国456def
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void fileInputStreamTest()
	{
		try 
		{
			//a.txt中内容为:abc中国def
			FileInputStream is = new FileInputStream("C:\\a.txt");
			byte[] buff = new byte[is.available()];
			is.read(buff);
			
			System.out.println(new String(buff, "UTF-8")); //输出结果为:abc123?й?456def
			System.out.println(new String(buff, "GB2312")); //输出结果为:abc123中国456def
			System.out.println(new String(buff, "GBK")); //输出结果为:abc123中国456def
			
			is.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

      采用不同的编码,输出结果是不一样的,有的会是乱码形式。至于采用什么样的编码,应该跟操作系统的字符编码有关。

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值