How can I convert the data in .txt file into byte array in android?

时间:2016-05-17 11:08:39

标签: android file bytearray

I have a txt file which contains values like 7F 7F 80 80 80 7F 7F 80 80 7F 7F 7F 80 7F 7F 7F etc. I want to store these values on a byte array such a way that bytes[0]=0x7f,bytes[1]=0x7f, bytes[2]=0x80,bytes[3]=0x80 and so on where bytes[length] is the byte array. When using the link https://examples.javacodegeeks.com/core-java/io/fileinputstream/read-file-in-byte-array-with-fileinputstream/ I can print the values using 'system.out.print' as 7F 7F 80 80 80 7F 7F 80 and so on. But when printing the byte array I am getting log

5-17 16:03:32.464  11892-11892/com.example.audiosend E/bytes﹕ 13
05-17 16:03:32.464  11892-11892/com.example.audiosend E/bytes﹕ 10  
05-17 16:03:32.465  11892-11892/com.example.audiosend E/bytes﹕ 55
05-17 16:03:32.465  11892-11892/com.example.audiosend E/bytes﹕ 70
05-17 16:03:32.465  11892-11892/com.example.audiosend E/bytes﹕ 32
05-17 16:03:32.465  11892-11892/com.example.audiosend E/bytes﹕ 13

How can I store the correct value of byte array from the txt file?

1 个答案:

答案 0 :(得分:0)

Try this,

import javax.xml.bind.DatatypeConverter;

public static String toHexString(byte[] array) {
   return DatatypeConverter.printHexBinary(array);
}

public static byte[] toByteArray(String s) {
   return DatatypeConverter.parseHexBinary(s);
}

DatatypeConverter - download here