033.byte[]与String互转不一致引起的bug
作者:互联网
1.结论
Java中String内置的public String(byte[] bytes)和public byte[] getBytes()对于不合法的utf-8字节流在解析时会增删字节。
2.为什么会出现这样的bug?
(1)首先准备这样的一段文本aaa.txt
China WangLei WangTao 3,USA jordan alex 1,Australia kobe james 2,UK Dale Tracy 4
(2)Team.java
package com.test.demo;
public class Team
{
public int teamRanking;//球队排名
public Team()
{
}
public Team(int teamRanking)
{
this.teamRanking = teamRanking;
}
public int getTeamRanking()
{
return teamRanking;
}
public void setTeamRanking(int teamRanking)
{
this.teamRanking = teamRanking;
}
}
(3)TeamMain.java
package com.test.demo;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
public class TestMain
{
public int inDataTeamArraylist(String fileName) throws IOException
{
FileInputStream fisRead = new FileInputStream(fileName);
byte[] byteRead = new byte[1000];
fisRead.read(byteRead);
fisRead.close();
String stringRead = new String(byteRead);
String[] stringArray = stringRead.split(",");//这里获取到的是4个String字符串
for (int i = 0; i < stringArray.length; i++)
{
System.out.println(Integer.parseInt(stringArray[i].split(" ")[3]));
}
return 0;
}
public static void main(String[] args) throws IOException
{
String file = "D:\\idea\\storehouse\\Item\\untitledTest\\src\\com\\test\\demo\\aaa.txt";
TestMain testMain = new TestMain();
System.out.println(testMain.inDataTeamArraylist(file));
}
}
(4)运行结果,报错的原因就是,byte[]与String互转不一致引起的bug
(5)改正后的TestMain.java
package com.test.demo;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
public class TestMain
{
public String inDataTeamArraylist(String fileName) throws IOException
{
FileInputStream fisRead = new FileInputStream(fileName);
StringBuilder stringBuilder = new StringBuilder(100);
int ch;
while ((ch = fisRead.read()) != -1)
{
stringBuilder.append((char)ch);
}
fisRead.close();
String[] stringArray = stringBuilder.toString().split(",");//这里获取到的是4个String字符串
for (int i = 0; i < stringArray.length; i++)
{
System.out.println(Integer.parseInt(stringArray[i].split(" ")[3]));
}
return "成功了呀!!!";
}
public static void main(String[] args) throws IOException
{
String file = "D:\\idea\\storehouse\\Item\\untitledTest\\src\\com\\test\\demo\\aaa.txt";
TestMain testMain = new TestMain();
System.out.println(testMain.inDataTeamArraylist(file));
}
}
(6)修改后的运行结果
标签:java,String,int,new,互转,033,teamRanking,public 来源: https://www.cnblogs.com/LLL0617/p/16660253.html