write String via OutputStream - Java java.io

Java examples for java.io:OutputStream

Description

write String via OutputStream

Demo Code


//package com.java2s;

import java.io.IOException;

import java.io.OutputStream;

public class Main {
    public static void writeString(String s, OutputStream out)
            throws IOException {
        if (s == null) {
            writeInt(0, out);/*from  w w  w  .  j a v  a  2 s. c om*/
            return;
        }
        int len = s.length();
        writeInt(len, out);
        for (int i = 0; i < len; i++)
            writChar(s.charAt(i), out);
    }

    public static void writeInt(int val, OutputStream out)
            throws IOException {
        out.write((val >>> 24) & 0xff);
        out.write((val >>> 16) & 0xff);
        out.write((val >>> 8) & 0xff);
        out.write(val & 0xff);
    }

    public static void writChar(char val, OutputStream out)
            throws IOException {
        out.write((val >>> 8) & 0xff);
        out.write(val & 0xff);
    }
}

Related Tutorials