0

I have a hadoop job for which its final output is the following

String myKey = "myKey";
context.write(myKey, myObjectWritable.toByteArray());

My output file look like the following

myKey/t00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

my question is how do I convert the bytes in string to a byte[] since the file is consist of string and bytes that is written as string.

    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[]

       }
user10714010
  • 865
  • 2
  • 13
  • 20
  • The `String` class has a `getBytes()` methd – smac89 Oct 09 '19 at 18:35
  • Possible duplicate of [How to convert Java String into byte\[\]?](https://stackoverflow.com/questions/18571223/how-to-convert-java-string-into-byte) – smac89 Oct 09 '19 at 18:36
  • If you write the file as binary (non-string), read the file as a binary(non-binary). the InputStream and OutputStream classes let you read() and write() bytes. All that said, if the data is actually a string, use TextReader and TextWriter and let the built-in behavior work for you – Gus Oct 09 '19 at 18:39

2 Answers2

0

To read you should revert the write process. If you invented writing yourself - do reading yourself. Otherwise consider ObjectOutputStream for writing, ObjectInputStream for reading and the whole Serializable protocol.

Example for writing

        try(ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(file))){
            stream.writeObject("Key");
            stream.writeObject("Value");
            stream.flush();
        }

and for corresponding reading

        try(ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))){
            String key = (String) objectInputStream.readObject();
            String value = (String) objectInputStream.readObject();
        }

These guys will do all the job for any object, whos class implements Serializable, like HashMap and most of the util things you mostly use.

lotor
  • 1,060
  • 7
  • 18
0
String mykey = "myKey";
byte[] mykey_byte_array = mykey.getBytes(StandardCharsets.UTF_8); 
System.out.println("contents of byte array " + Arrays.toString(mykey_byte_array));
Karan
  • 695
  • 1
  • 6
  • 16