昨天晚上研究了一点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();
}
}
}
采用不同的编码,输出结果是不一样的,有的会是乱码形式。至于采用什么样的编码,应该跟操作系统的字符编码有关。