简体   繁体   中英

Java: how to write short array like a byte array in a file

I want to add this table in a file:

public static final short[] FMW = {0x18, 0xC1, 0x00, 0x00, 0x36, 0xC1, 0x00}

I need to use a short array, because 0xC1 value is not recognized like a byte.

Then, I want to put this array in my file:

DataOutputStream out = null;
try {
   out = new DataOutputStream(new FileOutputStream(file));
   for (short anInt : FMW)
      out.write((byte)anInt);
   out.close();
} catch (IOException e) {
...

But when I read this file content after that, it's not correct:

try {
  FileReader reader = new FileReader(file);
  if (file.length() < offset+count) count = (int)(file.length() - offset);
  char[] rawdata = new char[count];
  reader.read(rawdata, 0, FMW.length);
  ...

My rawdata contains:

[0] : 0x18
[1] : 0xFFFD
[2] : 0x00
[3] : 0x00
[4] : 0x36
[5] : 0xFFFD
[6] : 0x00

Thanks for your help !

I have also faced a similar type of problem then I have written a method that takes a short[] array and returns a byte[] array -

public byte[] shortToByte(short[] shortInts) {
    int j=0;
    int length=shortInts.length;
    byte[] byteData=new byte[length*2];
    for (int i=0;i<length;i++) {
      byteData[j++]=(byte)(shortInts[i]>>>8);
      byteDataj++]=(byte)(shortInts[i]>>>0);
    }
    return byteData;
  }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM