在java中,如何将文件中的字节转换为对象?
我有一个hadoop作业,其最终输出如下在java中,如何将文件中的字节转换为对象?,java,Java,我有一个hadoop作业,其最终输出如下 String myKey = "myKey"; context.write(myKey, myObjectWritable.toByteArray()); myKey/t00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 我的输出文件如下所示 String myKey = "myKey"; context.write(myKey, myObjectWritable.toByteArray()); myKey/t
String myKey = "myKey";
context.write(myKey, myObjectWritable.toByteArray());
myKey/t00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
我的输出文件如下所示
String myKey = "myKey";
context.write(myKey, myObjectWritable.toByteArray());
myKey/t00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
我的问题是如何将字符串中的字节转换为byte[]
,因为文件由字符串和作为字符串写入的字节组成
try (BufferedReader br = new BufferedReader(new FileReader("my_map_reduce_file"))) {
String line;
while ((line = br.readLine()) != null) {
String[] x = line.split("\t");
// how do I convert x[1] to byte[]
}
要读取,应还原写入过程。如果你自己发明了写作,那就自己阅读吧。否则,请考虑<代码> ObjutOutsFuts用于编写,<代码> ObjutsIdvsStuts用于阅读和整个协议。 写作范例
try(ObjectOutputStream=newobjectoutputstream(newfileoutputstream(file))){
stream.writeObject(“Key”);
stream.writeObject(“值”);
stream.flush();
}
和相应的读数
try(ObjectInputStream ObjectInputStream=newobjectinputstream(newfileinputstream(file))){
字符串键=(字符串)objectInputStream.readObject();
字符串值=(字符串)objectInputStream.readObject();
}
这些家伙会为任何对象做所有的工作,谁的类实现了
Serializable
,比如HashMap和大多数你常用的util东西。String类有一个getBytes()
methdp可能的副本,如果你把文件写成二进制(非字符串),就把文件读成二进制(非二进制)。InputStream和OutputStream类允许您读取()和写入()字节。综上所述,如果数据实际上是一个字符串,请使用TextReader和TextWriter,让内置行为为您工作
String mykey = "myKey";
byte[] mykey_byte_array = mykey.getBytes(StandardCharsets.UTF_8);
System.out.println("contents of byte array " + Arrays.toString(mykey_byte_array));