Redirect standard output in Java
--------------- Redirect.java ------------------
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.FileDescriptor;
import java.io.File;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.text.SimpleDateFormat;
import javafx.application.*;
import javafx.scene.*;
import javafx.scene.image.*;
import javafx.scene.paint.*;
import javafx.scene.text.*;
import javafx.scene.canvas.*;
import javafx.embed.swing.*;
public class Redirect {
static void systemOut() { systemOut("output.txt", Charset.defaultCharset(), Charset.defaultCharset()); }
static void systemOut(String fileName, Charset charSetFile, Charset charSetConsole) {
try {
String base = StandardCharsets.UTF_8.name();
PrintStream st = new PrintStream(new ByteArrayOutputStream() {
PrintStream psFile = new PrintStream(new FileOutputStream(fileName));
PrintStream psConsole = new PrintStream(new FileOutputStream(FileDescriptor.out));
{ psFile.write((new SimpleDateFormat("dd.MM.yy HH:mm:ss").format(new Date()) +
System.getProperty("line.separator")).getBytes(charSetFile)); }
@Override
public void flush() {
try {
//writeTo(psFile); //Without decoding
//writeTo(psConsole);
String s = toString(base);
psFile.write(s.getBytes(charSetFile));
psConsole.write(s.getBytes(charSetConsole));
} catch (Exception e) { e.printStackTrace(); }
reset();
}
@Override
public void close() {
psFile.close();
}
}, true, base);
System.setOut(st);
System.setErr(st);
} catch (Exception e) { e.printStackTrace(); }
}
public static void main(String[] args) {
systemOut();
new JFXPanel();
Platform.runLater(() -> {
int w = 79, h = 25;
Canvas canvas = new Canvas(w, h);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, w, h);
gc.setFill(Color.BLACK);
gc.setFont(Font.font(24));
gc.fillText("Java", 16, 19);
WritableImage image = canvas.snapshot(new SnapshotParameters(), null);
PixelReader pixelReader = image.getPixelReader();
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
System.out.print(pixelReader.getColor(x, y).getBrightness() < 1 ? "*" : " ");
}
System.out.println();
}
Platform.exit();
System.exit(0);
});
}
}