Java 将ByteArray转换为固定长度字符串时遇到异常
我想把字节转换成字符串 我有一个android应用程序,我正在使用Java 将ByteArray转换为固定长度字符串时遇到异常,java,android,bytearray,Java,Android,Bytearray,我想把字节转换成字符串 我有一个android应用程序,我正在使用flatfile进行数据存储 假设我的平面文件中有很多记录 在平面文件数据库中,我的记录大小是固定的,其10个字符,在这里我按顺序存储了大量字符串记录 但当我从平面文件中读取一条记录时,每条记录的字节数是固定的。因为我为每条记录写了10个字节 如果我的字符串是S=“abc123” 然后将其存储在平面文件中,如每个字符的abc123 ASCII值,其余为0。 表示字节数组应该是[97,98,99,49,50,51,0,0,0]。 因
flatfile
进行数据存储
假设我的平面文件中有很多记录
在平面文件数据库中,我的记录大小是固定的,其10
个字符,在这里我按顺序存储了大量字符串记录
但当我从平面文件中读取一条记录时,每条记录的字节数是固定的。因为我为每条记录写了10个字节
如果我的字符串是S=“abc123”代码>
然后将其存储在平面文件中,如每个字符的abc123 ASCII值,其余为0。
表示字节数组应该是[97,98,99,49,50,51,0,0,0]
。
因此,当我想从字节数组中获取实际字符串时,我正在使用下面的代码,它工作正常
但当我给出我的inputString=“1234567890”
时,就会产生问题
public class MainActivity extends Activity {
public static short messageNumb = 0;
public static short appID = 16;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// record with size 10 and its in bytes.
byte[] recordBytes = new byte[10];
// fill record by 0's
Arrays.fill(recordBytes, (byte) 0);
// input string
String inputString = "abc123";
int length = 0;
int SECTOR_LENGTH = 10;
// convert in bytes
byte[] inputBytes = inputString.getBytes();
// set how many bytes we have to write.
length = SECTOR_LENGTH < inputBytes.length ? SECTOR_LENGTH
: inputBytes.length;
// copy bytes in record size.
System.arraycopy(inputBytes, 0, recordBytes, 0, length);
// Here i write this record in the file.
// Now time to read record from the file.
// Suppose i read one record from the file successfully.
// convert this read bytes to string which we wrote.
Log.d("TAG", "String is = " + getStringFromBytes(recordBytes));
}
public String getStringFromBytes(byte[] inputBytes) {
String s;
s = new String(inputBytes);
return s = s.substring(0, s.indexOf(0));
}
}
那么,当我的字符串长度为10时,我能做什么呢
我有两个解决方案-我可以检查我的inputBytes.length==10
然后使其不执行子字符串条件,否则检查在字节数组中包含0
但是我不想使用这个解决方案,因为我在我的应用程序中的很多地方都使用了这个东西。那么,有没有其他方法来实现这一目标
请给我推荐一些在任何情况下都有效的解决方案。我认为第二个解决方案会很好。(检查包含字节数组中的0,然后应用子字符串函数)。我认为这一行导致了错误
s = s.substring(0, s.indexOf(0));
s.indexOf(0)
返回-1,也许您应该指定ASCII码
对于48
所以这将工作s=s.substring(0,s.indexOf(48))代码>
检查indexOf(int)的文档
public int indexOf(int c)Since:API级别1在此字符串中搜索
用于指定字符的第一个索引。搜索
角色从开头开始,向结尾移动
绳子
参数c是要查找的字符。返回此字符串中的索引
如果找不到指定字符,则为-1
公共字符串getStringFromBytes(字节[]inputBytes){
字符串s;
s=新字符串(inputBytes);
int zerodex=s.indexOf(0);
返回zeroIndex<0?s:s.substring(0,zeroIndex);
}
使用SQLite作为数据库不是更容易、更快吗?这里的indexOf(0)
和indexOf(48)
是不同的事情。因此indexOf(48)
将不起作用
s = s.substring(0, s.indexOf(0));
s.indexOf(0)
public String getStringFromBytes(byte[] inputBytes) {
String s;
s = new String(inputBytes);
int zeroIndex = s.indexOf(0);
return zeroIndex < 0 ? s : s.substring(0, zeroIndex);
}