如何在hadoop中序列化对象(在HDFS中)

我有一个HashMap <String,ArrayList >。 我想将我的HashMap对象(hmap)序列化为HDFS位置,然后在Mapper和Reducers中对其进行反序列化以便使用它。

为了在HDFS上序列化我的HashMap对象,我使用了普通的java对象序列化代码,如下所示但是出错了(权限被拒绝)

try { FileOutputStream fileOut =new FileOutputStream("hashmap.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(hm); out.close(); } catch(Exception e) { e.printStackTrace(); } 

我得到以下exception

 java.io.FileNotFoundException: hashmap.ser (Permission denied) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.(FileOutputStream.java:221) at java.io.FileOutputStream.(FileOutputStream.java:110) at KMerIndex.createIndex(KMerIndex.java:121) at MyDriverClass.formRefIndex(MyDriverClass.java:717) at MyDriverClass.main(MyDriverClass.java:768) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.hadoop.util.RunJar.run(RunJar.java:221) at org.apache.hadoop.util.RunJar.main(RunJar.java:136) 

有人可以建议或分享如何在hdfs上的hadoop中序列化对象的示例代码吗?

请尝试使用Apache Commons Lang的SerializationUtils 。

以下是方法

 static Object clone(Serializable object) //Deep clone an Object using serialization. static Object deserialize(byte[] objectData) //Deserializes a single Object from an array of bytes. static Object deserialize(InputStream inputStream) //Deserializes an Object from the specified stream. static byte[] serialize(Serializable obj) //Serializes an Object to a byte array for storage/serialization. static void serialize(Serializable obj, OutputStream outputStream) //Serializes an Object to the specified stream. 

存储到HDFS时,您可以存储从序列化返回的byte[] 。 在获取Object时,您可以为ex:File对象键入强制转换为相应的对象,并可以将其取回。

在我的例子中,我在Hbase列中存储了一个hashmap,我将其检索回来,在我的mapper方法中为Hashmap,因为它是成功的。

当然,你也可以用同样的方式做到这一点……

另一件事是你也可以使用Apache Commons IO 参考这个 ( org.apache.commons.io.FileUtils ); 但是稍后您需要将此文件复制到HDFS。 因为您希望HDFS作为数据存储区。

 FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray); 

注意:两个jar apache commons io和apache commons lang总是在hadoop集群中可用。