Java tutorial
//package com.java2s; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; public class Main { public static void writeCString(OutputStream out, String s) throws IOException { writeCString(out, s, "utf-8"); } public static void writeCString(OutputStream os, String s, String characterSet) throws IOException { if (s == null || s.length() == 0) { os.write(0); return; } if (characterSet == null) { characterSet = "utf-8"; } byte[] bytes = s.getBytes(characterSet); writeCLenData(os, bytes); } public static void writeCString(OutputStream out, String s, int fixedLen) throws IOException { byte[] bytes = s.getBytes(); out.write(bytes.length); fixedLen -= 1; if (fixedLen <= 0) return; if (fixedLen <= bytes.length) { out.write(bytes, 0, fixedLen); } else { out.write(bytes); byte[] fillBytes = new byte[fixedLen - bytes.length]; Arrays.fill(fillBytes, (byte) 0); out.write(fillBytes); } out.flush(); } public static void writeCString(OutputStream out, String s, String characterSet, int fixedLen) throws IOException { byte[] bytes = s.getBytes(characterSet); out.write(bytes.length); fixedLen -= 1; if (fixedLen <= 0) return; if (fixedLen <= bytes.length) { out.write(bytes, 0, fixedLen); } else { out.write(bytes); byte[] fillBytes = new byte[fixedLen - bytes.length]; Arrays.fill(fillBytes, (byte) 0); out.write(fillBytes); } out.flush(); } public static void writeCLenData(OutputStream os, byte[] bytes) throws IOException { if (bytes == null) { os.write(0); } else { os.write(bytes.length); os.write(bytes); } } }