MATSIM
ByteBufferUtils.java
Go to the documentation of this file.
1 /* *********************************************************************** *
2  * project: org.matsim.*
3  * ByteBufferUtils.java
4  * *
5  * *********************************************************************** *
6  * *
7  * copyright : (C) 2009 by the members listed in the COPYING, *
8  * LICENSE and WARRANTY file. *
9  * email : info at matsim dot org *
10  * *
11  * *********************************************************************** *
12  * *
13  * This program is free software; you can redistribute it and/or modify *
14  * it under the terms of the GNU General Public License as published by *
15  * the Free Software Foundation; either version 2 of the License, or *
16  * (at your option) any later version. *
17  * See also COPYING, LICENSE and WARRANTY file *
18  * *
19  * *********************************************************************** */
20 
21 package org.matsim.core.utils.misc;
22 
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
25 import java.io.IOException;
26 import java.io.ObjectInputStream;
27 import java.io.ObjectOutput;
28 import java.io.ObjectOutputStream;
29 import java.io.Serializable;
30 import java.nio.ByteBuffer;
31 
37 public class ByteBufferUtils {
38 
47  public static void putString(final ByteBuffer buffer, final String string) {
48  buffer.putInt(string.length());
49  for (int i = 0; i < string.length(); i++) {
50  buffer.putChar(string.charAt(i));
51  }
52  }
53 
62  public static String getString(final ByteBuffer buffer) {
63  int length = buffer.getInt();
64  char[] chBuffer = new char[length];
65  for (int i = 0; i < length; i++) {
66  chBuffer[i] = buffer.getChar();
67  }
68  return new String(chBuffer);
69  }
70 
77  public static void putObject(final ByteBuffer buffer, Serializable o){
78  try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
79  try (ObjectOutput oout = new ObjectOutputStream(bos)) {
80  oout.writeObject(o);
81  byte[] laneBytes = bos.toByteArray();
82  buffer.putInt(laneBytes.length);
83  for (int i = 0; i < laneBytes.length; i++) {
84  buffer.put(laneBytes[i]);
85  }
86  }
87  } catch (IOException e) {
88  e.printStackTrace();
89  }
90  }
91 
97  public static Object getObject(ByteBuffer buffer) {
98  int length = buffer.getInt();
99  byte[] bytes = new byte[length];
100  for (int i = 0; i < length; i++) {
101  bytes[i] = buffer.get();
102  }
103  try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
104  ObjectInputStream oin = new ObjectInputStream(bis)) {
105  return oin.readObject();
106  } catch (IOException | ClassNotFoundException e) {
107  e.printStackTrace();
108  return null;
109  }
110  }
111 
112 }
static Object getObject(ByteBuffer buffer)
static String getString(final ByteBuffer buffer)
static void putObject(final ByteBuffer buffer, Serializable o)
static void putString(final ByteBuffer buffer, final String string)