PrefixPrintStream extends PrintStream { public PrefixPrintStream(OutputStream out, String prefix) { super(out, true); this.prefix = prefix; } PrefixPrintStream(OutputStream out, String prefix); @Override void println(); @Override void println(boolean x); @Override void println(char x); @Override void println(int x); @Override void println(long x); @Override void println(float x); @Override void println(double x); @Override void println(char[] x); @Override void println(String x); @Override void println(Object x); @Override void flush(); @Override void write(int c); @Override void write(byte[] buf, int off, int len); @Override void write(byte[] buf); void write(String s); @Override PrintStream printf(String format, Object... args); @Override PrintStream printf(Locale l, String format, Object... args); @Override PrintStream format(String format, Object... args); @Override PrintStream format(Locale l, String format, Object... args);  }
@Test public void testPrefixPrintStream() throws IOException { File file = File.createTempFile("TestPrefixPrintStream", "txt"); FileOutputStream fos = new FileOutputStream(file); String nl = System.getProperty("line.separator"); String expectedResult = "AAABBB1234" + nl + "AAABBB1234" + nl + "AAABBB1234" + nl; PrefixPrintStream pps = new PrefixPrintStream(new PrefixPrintStream(fos, "AAA"), "BBB"); for (int i = 0; i < 3; i++) { pps.print("1"); pps.print("2"); pps.print("3"); pps.println("4"); } pps.flush(); pps.close(); String output = FileUtils.readFileToString(file); System.out.println(output); Assert.assertEquals(expectedResult, output); }