List of usage examples for java.io DataOutputStream DataOutputStream
public DataOutputStream(OutputStream out)
From source file:J2MEWriteReadMixedDataTypesExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);/*from ww w. ja v a2 s . c o m*/ notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); byte[] outputRecord; String outputString = "First Record"; int outputInteger = 15; boolean outputBoolean = true; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); outputDataStream.writeUTF(outputString); outputDataStream.writeBoolean(outputBoolean); outputDataStream.writeInt(outputInteger); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); outputStream.reset(); outputStream.close(); outputDataStream.close(); String inputString = null; int inputInteger = 0; boolean inputBoolean = false; byte[] byteInputData = new byte[100]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); for (int x = 1; x <= recordstore.getNumRecords(); x++) { recordstore.getRecord(x, byteInputData, 0); inputString = inputDataStream.readUTF(); inputBoolean = inputDataStream.readBoolean(); inputInteger = inputDataStream.readInt(); inputStream.reset(); } inputStream.close(); inputDataStream.close(); alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); recordstore.closeRecordStore(); if (RecordStore.listRecordStores() != null) { RecordStore.deleteRecordStore("myRecordStore"); } } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } }
From source file:io.dacopancm.socketdcm.net.StreamSocket.java
public void handle() { try {//from ww w . ja v a 2 s . c om if (ConectType.GET_STREAMLIST.name().equalsIgnoreCase(method)) { DataOutputStream dOut = new DataOutputStream(sock.getOutputStream()); DataInputStream dIn = new DataInputStream(sock.getInputStream()); String files = HelperUtil.toJSON(mainApp.getStreamFilesList().toArray()); dOut.writeUTF(files); dOut.flush(); // Send off the data dOut.close(); } else if (ConectType.GET_STREAM.name().equalsIgnoreCase(method)) { DataOutputStream dOut = new DataOutputStream(sock.getOutputStream()); DataInputStream dIn = new DataInputStream(sock.getInputStream()); boolean player = mainApp.playStream(streamid); dOut.writeUTF("" + (player ? HelperUtil.VLC_SRV_PORT : player)); dOut.flush(); // Send off the data dOut.close(); } } catch (IOException ex) { HelperUtil.showErrorB("No se pudo establecer conexin"); try { if (sock != null) { sock.close(); } } catch (IOException e) { } } }
From source file:com.ning.arecibo.util.timeline.times.TimesAndSamplesCoder.java
public static byte[] combineTimesAndSamples(final byte[] times, final byte[] samples) { final int totalSamplesSize = 4 + times.length + samples.length; final ByteArrayOutputStream baStream = new ByteArrayOutputStream(totalSamplesSize); final DataOutputStream outputStream = new DataOutputStream(baStream); try {/* w ww . j a v a 2s . c om*/ outputStream.writeInt(times.length); outputStream.write(times); outputStream.write(samples); outputStream.flush(); return baStream.toByteArray(); } catch (IOException e) { throw new IllegalStateException(String.format( "Exception reading timeByteCount in TimelineChunkMapper.map() for times %s, samples %s", Hex.encodeHex(times), Hex.encodeHex(samples)), e); } }
From source file:gribbit.util.RequestBuilder.java
/** * Make a GET or POST request, handling up to 6 redirects, and return the response. If isBinaryResponse is true, * returns a byte[] array, otherwise returns the response as a String. *//* w ww . j a va 2 s . c o m*/ private static Object makeRequest(String url, String[] keyValuePairs, boolean isGET, boolean isBinaryResponse, int redirDepth) { if (redirDepth > 6) { throw new IllegalArgumentException("Too many redirects"); } HttpURLConnection connection = null; try { // Add the URL query params if this is a GET request String reqURL = isGET ? url + "?" + WebUtils.buildQueryString(keyValuePairs) : url; connection = (HttpURLConnection) new URL(reqURL).openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod(isGET ? "GET" : "POST"); connection.setUseCaches(false); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/43.0.2357.125 Safari/537.36"); if (!isGET) { // Send the body if this is a POST request connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); String params = WebUtils.buildQueryString(keyValuePairs); connection.setRequestProperty("Content-Length", Integer.toString(params.length())); try (DataOutputStream w = new DataOutputStream(connection.getOutputStream())) { w.writeBytes(params); w.flush(); } } if (connection.getResponseCode() == HttpResponseStatus.FOUND.code()) { // Follow a redirect. For safety, the params are not passed on, and the method is forced to GET. return makeRequest(connection.getHeaderField("Location"), /* keyValuePairs = */null, /* isGET = */ true, isBinaryResponse, redirDepth + 1); } else if (connection.getResponseCode() == HttpResponseStatus.OK.code()) { // For 200 OK, return the text of the response if (isBinaryResponse) { ByteArrayOutputStream output = new ByteArrayOutputStream(32768); IOUtils.copy(connection.getInputStream(), output); return output.toByteArray(); } else { StringWriter writer = new StringWriter(1024); IOUtils.copy(connection.getInputStream(), writer, "UTF-8"); return writer.toString(); } } else { throw new IllegalArgumentException( "Got non-OK HTTP response code: " + connection.getResponseCode()); } } catch (Exception e) { throw new IllegalArgumentException( "Exception during " + (isGET ? "GET" : "POST") + " request: " + e.getMessage(), e); } finally { if (connection != null) { try { connection.disconnect(); } catch (Exception e) { } } } }
From source file:Main.java
public static byte[] convertToB64(float[] a) { ByteArrayOutputStream os = new ByteArrayOutputStream(a.length * 4 + 2); DataOutputStream dou = new DataOutputStream(os); try {/*from w w w. j a v a2 s . c o m*/ for (int i = 0; i < a.length; i++) dou.writeFloat(a[i]); return encode(os.toByteArray()); } catch (Exception s) { return null; } }
From source file:com.ibm.mobilefirst.mobileedge.utils.RequestUtils.java
public static void executeTrainRequest(String name, String uuid, List<AccelerometerData> accelerometerData, List<GyroscopeData> gyroscopeData, RequestResult requestResult) throws IOException { URL url = new URL("https://medge.mybluemix.net/alg/train"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setReadTimeout(5000);//from ww w.j av a2 s . com conn.setConnectTimeout(10000); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoInput(true); conn.setDoOutput(true); JSONObject jsonToSend = createTrainBodyJSON(name, uuid, accelerometerData, gyroscopeData); OutputStream outputStream = conn.getOutputStream(); DataOutputStream wr = new DataOutputStream(outputStream); wr.writeBytes(jsonToSend.toString()); wr.flush(); wr.close(); outputStream.close(); String response = ""; int responseCode = conn.getResponseCode(); //Log.e("BBB2","" + responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } } else { response = "{}"; } handleResponse(response, requestResult); }
From source file:io.druid.data.input.impl.prefetch.RetryingInputStreamTest.java
@Before public void setup() throws IOException { testFile = temporaryFolder.newFile(); try (FileOutputStream fis = new FileOutputStream(testFile); GZIPOutputStream gis = new GZIPOutputStream(fis); DataOutputStream dis = new DataOutputStream(gis)) { for (int i = 0; i < 10000; i++) { dis.writeInt(i);//from w w w . j a va 2 s . c om } } throwError = false; final InputStream retryingInputStream = new RetryingInputStream<>(testFile, new ObjectOpenFunction<File>() { @Override public InputStream open(File object) throws IOException { return new TestInputStream(new FileInputStream(object)); } @Override public InputStream open(File object, long start) throws IOException { final FileInputStream fis = new FileInputStream(object); Preconditions.checkState(fis.skip(start) == start); return new TestInputStream(fis); } }, e -> e instanceof IOException, MAX_RETRY); inputStream = new DataInputStream(new GZIPInputStream(retryingInputStream)); throwError = true; }
From source file:ml.shifu.guagua.io.Bzip2BytableSerializer.java
/** * Serialize from object to bytes.//from w ww .j a v a2 s . c o m * * @throws NullPointerException * if result is null. * @throws GuaguaRuntimeException * if any io exception. */ @Override public byte[] objectToBytes(RESULT result) { ByteArrayOutputStream out = null; DataOutputStream dataOut = null; try { out = new ByteArrayOutputStream(); OutputStream gzipOutput = new BZip2CompressorOutputStream(out); dataOut = new DataOutputStream(gzipOutput); result.write(dataOut); } catch (IOException e) { throw new GuaguaRuntimeException(e); } finally { if (dataOut != null) { try { dataOut.close(); } catch (IOException e) { throw new GuaguaRuntimeException(e); } } } return out.toByteArray(); }
From source file:com.ning.arecibo.util.timeline.times.TimelineCoderImpl.java
/** * Convert the array of unix times to a compressed timeline, and return the byte array * representing that compressed timeline * @param times an int array giving the unix times to be compressed * @return the compressed timeline/*w w w. jav a2 s .c o m*/ */ @Override public byte[] compressDateTimes(final List<DateTime> times) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final DataOutputStream dataStream = new DataOutputStream(outputStream); try { int lastTime = 0; int lastDelta = 0; int repeatCount = 0; for (DateTime time : times) { final int newTime = DateTimeUtils.unixSeconds(time); if (lastTime == 0) { lastTime = newTime; writeTime(0, lastTime, dataStream); continue; } else if (newTime < lastTime) { log.warn("In TimelineCoder.compressTimes(), newTime {} is < lastTime {}; ignored", newTime, lastTime); continue; } final int delta = newTime - lastTime; final boolean deltaWorks = delta <= TimelineOpcode.MAX_DELTA_TIME; final boolean sameDelta = repeatCount > 0 && delta == lastDelta; if (deltaWorks) { if (sameDelta) { repeatCount++; if (repeatCount == MAX_SHORT_REPEAT_COUNT) { writeRepeatedDelta(delta, repeatCount, dataStream); repeatCount = 0; } } else { if (repeatCount > 0) { writeRepeatedDelta(lastDelta, repeatCount, dataStream); } repeatCount = 1; } lastDelta = delta; } else { if (repeatCount > 0) { writeRepeatedDelta(lastDelta, repeatCount, dataStream); } writeTime(0, newTime, dataStream); repeatCount = 0; lastDelta = 0; } lastTime = newTime; } if (repeatCount > 0) { writeRepeatedDelta(lastDelta, repeatCount, dataStream); } dataStream.flush(); return outputStream.toByteArray(); } catch (IOException e) { log.error("Exception compressing times list of length {}", times.size(), e); return null; } }
From source file:eu.stratosphere.pact.runtime.task.util.SerializationCopier.java
/** * Creates a SerializationCopier with an byte array of initial size 1024 byte. *///from ww w .j a va 2 s. c o m public SerializationCopier() { serializedCopy = new byte[1024]; baos = new ByteArrayOutputStream(); dos = new DataOutputStream(baos); bais = new ByteArrayInputStream(serializedCopy); dis = new DataInputStream(bais); }