JDChi
JDChi

Reputation: 260

Same code and same data but output different contents?

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

Upvotes: 1

Views: 68

Answers (1)

Jan Čern&#253;
Jan Čern&#253;

Reputation: 1386

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

Upvotes: 2

Related Questions