java中读取txt文件的数据并且最终返回byte类型数据

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.nutz.lang.Encoding;

public class ReadTxtData_ByteTransformString {
     public static void main(String[] args){
           // File file = new File("D:/test20180921_bits.txt");
            try {
                //下面多次转换的目的是:  检查转换之后  数据是否出现不一致
                byte[] str_byte= read("D:/test20180921_bits.txt");
                System.out.println("获取文本数据byte[] str_byte:"+new String(str_byte,Encoding.GBK));
                
                String strData = new String(str_byte,Encoding.GBK);
                System.out.println("获取文本数据 转换成String strData:"+strData);
                 
                //将字符串 转换成 byte数组 并且还原数据
                byte[] strByte = strData.getBytes("GBK"); 
                System.out.println("****再将String strData的数据还原到byte[] strByte:"+new String(strByte,Encoding.GBK));
                 
            } catch (IOException e) {
                e.printStackTrace();
            }
           
        }

  
    /*
     *读取txt文本数据  
     *
     */
    public static byte[] read(String fileName) throws IOException {
        InputStream is=new FileInputStream(fileName);
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        byte[] buffer=new byte[is.available()];
        int n=0;
        while((n=is.read(buffer))!=-1)
        bos.write(buffer,0,n);
        bos.close();
        is.close();
        return bos.toByteArray();
     }
}

本案例 已经过测试! 不得抄袭发表!

关于本文中使用的编码: 可以下载 此 nutz-1.r.62.jar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值