java读取文件内容时解析每行字符串String指定字节位置的数据

需求:在读取文件时,需要获取文件内容,且需要解析每行数据中指定字节位置的数据。例如文件前十位字节为姓名,后八位为生日,后一位为性别。

原计划:使用FileReader、BufferedReader逐行获取文件内容,然后再用String.substring()方法按照规则进一步解析每行数据的具体字段。

代码如下

    	File file = new File("D:/1.txt");
    	BufferedReader br = new BufferedReader(new FileReader(file));
    	String tmpStr = null;
    	while ((tmpStr=br.readLine())!=null) {
			String name = tmpStr.substring(0, 10);
			String birthday = tmpStr.substring(10, 18);
			String sex = tmpStr.substring(18, 19);
			System.out.println(name+";"+birthday+";"+sex);
		}

问题:解析数据时,使用String.substring()方法存在问题。即当数据中存在汉字时,一个汉字在substring方法中视为1位,而按照字节解析时并不是。

改进方案:将每一行字符串先解析成byte数组,然后再按照位置解析

代码如下

    	File file = new File("D:/1.txt");
    	BufferedReader br = new BufferedReader(new FileReader(file));
    	String tmpStr = null;
    	while ((tmpStr=br.readLine())!=null) {
    		byte[] tmpByte = tmpStr.getBytes(Charset.forName("GBK"));
			String name = new String(tmpByte,0,10,Charset.forName("GBK"));
			String birthday = new String(tmpByte,10, 8,Charset.forName("GBK"));
			String sex = new String(tmpByte,18, 1,Charset.forName("GBK"));
			System.out.println(name+";"+birthday+";"+sex);
		}

使用到的方法:public String(byte[] bytes, int offset, int length, String charsetName)。

相关参数说明:bytes - 要解码为字符的 byte;offset - 要解码的第一个 byte 的索引;length - 要解码的 byte 数;charsetName - 受支持 charset 的名称

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值