Java examples for java.io:OutputStream
Writes a string to the OutputStream formatted as a .NET string.
//package com.java2s; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; public class Main { /**// w w w . j a v a 2s . c o m * Writes a string to the stream formatted as a .NET string. * @param out The output stream * @param value The string to write * @throws IOException if an IO error occurs */ public static void writeString(final OutputStream out, String value) throws IOException { if (value == null) //Null check throw new NullPointerException("String cannot be null"); //System.out.printf("String: (Length: %s)\n", value.length()); write7BitEncodedInt(out, value.length()); //Write the length of the string byte[] bytes = value.getBytes(Charset.forName("utf-8")); out.write(bytes); //Write the string bytes //printBytes(bytes); } /** * Writes the integer to the stream as a 7 bit encoded integer * @param out The output stream * @param value The integer to write * @throws IOException if an IO error occurs */ public static void write7BitEncodedInt(final OutputStream out, int value) throws IOException { //Based on the .NET implementation. See http://referencesource.microsoft.com/#mscorlib/system/io/binarywriter.cs,407 //Write out an int 7 bits at a time. The high bit of the byte, when on, tells reader to continue reading more bytes. int v = value; while (v >= 0x80) { out.write(new byte[] { (byte) (v | 0x80) }); v >>= 7; } out.write(new byte[] { (byte) v }); } }