-1

I am trying to read a stdin from a WebExtentions application. The documentation says:

Each message is serialized using JSON, UTF-8 encoded and is preceded with a 32-bit value containing the message length in native byte order.

https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Native_messaging

They have an example in Python to read the message sent:

rawLength = sys.stdin.read(4)
if len(rawLength) == 0:
  sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
return json.loads(message)

So it removes the 32-bit number from the message and then gets the message. How can I do the same in Java?

Edit someone asked for me to attempt a translation. Please note I know little.

System.in.skip(4); // 4 bytes is 32 bits
Scanner sc = new Scanner(System.in);
String message = sc.next();

And it doesn't remove the 4 four bytes from the message. My only other solution is to find the last { symbol in the message (since it is a JSON object with only one key : value pair) and take the substring after that.

I Newton
  • 33
  • 5
  • Possible duplicate of [How to read integer value from the standard input in Java](http://stackoverflow.com/questions/2506077/how-to-read-integer-value-from-the-standard-input-in-java) – bhspencer Apr 28 '17 at 17:06
  • 2
    Pretty much the same way but using Java's io apis? What are you asking, specifically? – pvg Apr 28 '17 at 17:06
  • @bhspencer it's not a dupe of that, that question is about reading an ascii representation of an integer, this one is not. – pvg Apr 28 '17 at 17:08
  • I would guess by writing some java code? But not sure. – GhostCat Apr 28 '17 at 17:22
  • 1
    Hint: this is not a free code translation service. Show us what you tried to solve this yourself. – GhostCat Apr 28 '17 at 17:24
  • What does 'doesn't remove the 4 bytes' mean? What happens? What do you expect to happen? How are they different? Did you read the docs to `skip` at https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#skip(long)? – pvg Apr 28 '17 at 18:38

1 Answers1

0

To read the first 4 bytes from standard in as a 32 bit int do the following:

DataInputStream data = new DataInputStream(System.in);
int length = data.readInt();
bhspencer
  • 11,362
  • 4
  • 29
  • 38