Ad

Same Code And Same Data But Output Different Contents?

- 1 answer

I have below code which is used to write the list array into a dat file , I ran on OnePlus2 and the IDE is Android Studio 1.3.

private void writeToFile(List<Short> list) throws IOException {

    String stringTransform = transform(list);
    String str = new String(stringTransform.getBytes(), "ascii");
    byte[] bytes = new byte[str.length() / 8];
    char chatAt;
    for (int i = 0; i < str.length() / 8; i++) {
        for (int j = 0; j < 8; j++) {
            chatAt = str.charAt(i * 8 + j);
            if (chatAt == '1') {
                byte b = (byte) (0x80 >> j);
                bytes[i] = (byte) (bytes[i] | b);
            }
        }
    }
    FileOutputStream fos = new FileOutputStream("/sdcard/1.dat");
    fos.write(bytes);
    fos.close();
    fos.flush();


}
private String transform(List<Short> list) {
    StringBuilder sb = new StringBuilder(list.size());
    for (Short integer : list) {
        sb.append(integer);
    }

    return sb.toString();
}

However , I input the same data in different time , and the dat file which is generated will show different content , as the pictures show: enter image description here

enter image description here

Ad

Answer

This is not about your code. This is about program and encoding you using. Try to change encoding in your editor. If it is binary file I would recommend sublimetext 3 with HexViewer plugin:

Sublime text 3

Ad
source: stackoverflow.com
Ad