首页 > 基础教程 > IO流 > OutputStream类
Java ByteArrayOutputStream.toString()指定字符集转换为字符串
定义
public String toString()
public String toString(String charsetName)
public String toString(int hibyte)
参数
charsetName:指定字符集(utf-8,GB2312等)。
返回
从缓冲区内容解码的字符串。
异常
UnsupportedEncodingException :不支持指定的字符集
实例
public static void main(String args[]) throws Exception
{
InputStream in = null;
ByteArrayOutputStream out = null;
try
{
in = new FileInputStream(new File("c:\\51gjie.txt"));
out = new ByteArrayOutputStream();
byte[] bytes = new byte[1024 * 8];
int len = 0;
while((len = in .read(bytes)) != -1)
{
out.write(bytes, 0, len);
}
System.out.println(out.toString("GBK"));//使用GBK编码转换成字符串
}
catch(FileNotFoundException e)
{}
finally
{
try
{
out.close(); in .close();
}
catch(IOException e)
{}
}
}
ByteArrayOutputStream.toString通过使用指定的charsetName解码字节,将缓冲区的内容转换为字符串。 新String的长度是字符集的函数,因此可能不等于字节数组的长度。
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。