java - 如何将字节数组写入和读取到 DataInput 和 DataOutput Stream

标签 java hadoop bytearray hbase datainputstream

Hbase 充当我的 Map reduce 作业的源和接收器。我已经编写了名为(vector writable)的自定义可写类,它有两个字段。

private DoubleVector vector; // It is a Double Array
private byte[] rowKey;       // The row key of the Hbase 

我的映射器将它作为它的值发出,因此我在我的 vectorWritable 类中实现了写入和读取方法

  @Override
   public final void write(DataOutput out) throws IOException {
   writeVectorCluster(this.vector, this.rowKey, out);       
   }

   @Override
   public final void readFields(DataInput in) throws IOException {
   this.vector = readVector(in);
   this.rowKey = readRowKey(in);
   } 

public static void writeVectorCluster(DoubleVector vector, byte[] rowkey, DataOutput out)
            throws IOException {
        out.writeInt(vector.getLength());
            for (int i = 0; i < vector.getDimension(); i++) {
                out.writeDouble(vector.get(i));
            }
            int length = rowkey.length;
            out.writeInt(length);

           //Is this the right way ?
            out.write(rowkey);
        }


public static DoubleVector readVector(DataInput in) throws IOException {
        int length = in.readInt();
        DoubleVector vector = null;
            vector = new DenseDoubleVector(length);
            for (int i = 0; i < length; i++) {
                vector.set(i, in.readDouble());
            }
        return vector;
    }

   @SuppressWarnings("null")
    public static byte[] readRowKey(DataInput in) throws IOException {
        int length = in.readInt();
        byte [] test = null;
            for (int i = 0; i < length; i++) {
                // getting null pointer exception here
                test[i] = in.readByte();
            }
        return test;
    }

当我尝试从输入流中读取 rowKey 时,出现 NullPointerException。 readVector 方法工作正常,我得到了正确的值。

如何在 DataInput 流中写入字节数组,以便我可以在我的输出流中检索它

更新:已解决 这是我的 rowKey 方法的更新,效果很好。谢谢@Perception

public static byte[] readRowKey(DataInput in) throws IOException {  
        int length = in.readInt();
        byte[] theBytes = new byte[length];
        in.readFully(theBytes); 
        return theBytes;
    }

最佳答案

你没有初始化你的字节数组:

byte [] test = null;

应该是:

byte [] test = new byte[length];

关于java - 如何将字节数组写入和读取到 DataInput 和 DataOutput Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15781095/

相关文章:

java - Java 中的这段递归 lambda 调用是如何工作的

hadoop - ClassNotFoundException,在运行 Hadoop 示例作业时

hadoop - titan1.0.0 无法连接到 hadoop1.2.1

c# - ASP.NET 5(核心): How to store objects in session-cache (ISession)?

java - 自签名 Java Applet

java - Apache POI 3.6 : Reading an xlsx file

java - 向 JList 添加滚动条(包括 DefaultListModel 对象)

hadoop - Apache Hive如何识别分区是哪一列

java - Android:字节数组到十进制字符串

java - 如何将对象分解为 byte[]?