【问题标题】:Java: how to write short array like a byte array in a fileJava:如何在文件中编写像字节数组一样的短数组
【发布时间】:2015-03-05 21:14:07
【问题描述】:

我想将此表添加到文件中:

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

我需要使用一个短数组,因为 0xC1 值不像字节那样被识别。

然后,我想把这个数组放到我的文件中:

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

但是当我在那之后阅读这个文件内容时,它是不正确的:

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);
  ...

我的原始数据包含:

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

感谢您的帮助!

【问题讨论】:

    标签: java arrays file bytearray


    【解决方案1】:

    我也遇到过类似的问题,然后我编写了一个方法,该方法接受 short[] 数组并返回 byte[] 数组 -

    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;
      }  
    

    【讨论】:

    • 不,问题仍然存在:我有 0xFFFD 而不是 0xC1。
    猜你喜欢
    • 1970-01-01
    • 2010-12-18
    • 2015-09-04
    • 2012-05-14
    • 2013-11-04
    • 1970-01-01
    • 2021-06-17
    • 2011-08-14
    • 2019-10-29
    相关资源
    最近更新 更多