Console output to string java

How to capture and store console output, System.out.println()

In Java, every string that passes through System.out.println() is stored in System.out . So, to get all strings, simply use System.out.toString() function. You can also swap in and out the console stream using System.setOut() . Examples below show how to get all strings called by System.out.println() and swap with another console stream.

import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class ConsoleTutorial { public static void main(String[] args){ // Display something in initial console. System.out.println("One - Previous console"); // Preserve current console which contains 'One - Previous console'. PrintStream previousConsole = System.out; // Set the standard output to use newConsole. ByteArrayOutputStream newConsole = new ByteArrayOutputStream(); System.setOut(new PrintStream(newConsole)); // From here on, all System.out.println() calls will be stored in newConsole. // Note: The output "Two - New console" you see from the console doesn't // come from this line but from the line "previousConsole.println(. );" System.out.println("Two - New console"); previousConsole.println(newConsole.toString()); // Display output of newConsole. // Restore back the standard console output. System.setOut(previousConsole); // Test print to console. System.out.println("Three - Restored console"); System.out.println(newConsole.toString()); } }

Output

One - Previous console Two - New console Three - Restored console Two - New console

Github

Источник

Читайте также:  Java response streaming output

How to get a the output to a console as a string in java

First it replaces the standard output stream with special stream which memorizes the last string (assuming that strings end with ). Solution: If you’re running your Java program from the shell, you can redirect it’s output to a file using the ‘>’ operator.

How to get a the output to a console as a string in java

You could redirect the console prints to your own stream, see this answer!

I used Joacim Ericsson’s resource to solve my problem. First of all i created a Output stream for my text area which was where my data was going.

public class ConsoleRedirection extends OutputStream < private JTextArea textArea; public ConsoleRedirection(JTextArea textArea) < this.textArea = textArea; >@Override public void write(int b) throws IOException < textArea.append(String.valueOf((char)b)); >> 

Then i just created a print stream using my output stream and set System.out to my custom print stream.

 PrintStream printStream = new PrintStream(new ConsoleRedirection(console)); System.setOut(printStream); System.setErr(printStream); 

Redirect console output to string in Java, Here is a utility Class named ConsoleOutputCapturer. It allows the output to go to the existing console however behind the scene keeps capturing the output text. You can control what to capture with the start/stop methods. In other words call start to start capturing the console output and once you are … Code sampleByteArrayOutputStream baos = new ByteArrayOutputStream();PrintStream ps = new PrintStream(baos);PrintStream old = System.out;System.setOut(ps);System.out.println(«Foofoofoo!»);Feedback

How could I read Java Console Output into a String buffer

Ok, this was a fun problem. Dosen’t seem to be an elegant way of solving it for all PrintStream methods at once. (Unfortunately there is no FilterPrintStream .)

Читайте также:  Метод прогонки python numpy

I did write up an ugly reflection-based workaround though (not to be used in production code I suppose 🙂

class LoggedPrintStream extends PrintStream < final StringBuilder buf; final PrintStream underlying; LoggedPrintStream(StringBuilder sb, OutputStream os, PrintStream ul) < super(os); this.buf = sb; this.underlying = ul; >public static LoggedPrintStream create(PrintStream toLog) < try < final StringBuilder sb = new StringBuilder(); Field f = FilterOutputStream.class.getDeclaredField("out"); f.setAccessible(true); OutputStream psout = (OutputStream) f.get(toLog); return new LoggedPrintStream(sb, new FilterOutputStream(psout) < public void write(int b) throws IOException < super.write(b); sb.append((char) b); >>, toLog); > catch (NoSuchFieldException shouldNotHappen) < >catch (IllegalArgumentException shouldNotHappen) < >catch (IllegalAccessException shouldNotHappen) < >return null; > > 

. that can be used like this:

hello 5 Some error ----- Log for System.out: ----- hello 5 ----- Log for System.err: ----- Some error 

(Note though, that the out field in FilterOutputStream is protected and documented, so it is part of the API 🙂

You can’t do that once the program is finished running. You need to do it before the program starts to write output.

See this article (archive.org) for details on how to replace stdout and stderr. The core calls are System.setOut() and System.setErr() .

You can use PipedInputStream and PipedOutputStream.

//create pairs of Piped input and output streasm for std out and std err final PipedInputStream outPipedInputStream = new PipedInputStream(); final PrintStream outPrintStream = new PrintStream(new PipedOutputStream( outPipedInputStream)); final BufferedReader outReader = new BufferedReader( new InputStreamReader(outPipedInputStream)); final PipedInputStream errPipedInputStream = new PipedInputStream(); final PrintStream errPrintStream = new PrintStream(new PipedOutputStream( errPipedInputStream)); final BufferedReader errReader = new BufferedReader( new InputStreamReader(errPipedInputStream)); final PrintStream originalOutStream = System.out; final PrintStream originalErrStream = System.err; final Thread writingThread = new Thread(new Runnable() < @Override public void run() < try < System.setOut(outPrintStream); System.setErr(errPrintStream); // You could also set the System.in here using a // PipedInputStream DoSomething(); // Even better would be to refactor DoSomething to accept // PrintStream objects as parameters to replace all uses of // System.out and System.err. DoSomething could also have // an overload with DoSomething() calling: DoSomething(outPrintStream, errPrintStream); >finally < // may also want to add a catch for exceptions but it is // essential to restore the original System output and error // streams since it can be very confusing to not be able to // find System.out output on your console System.setOut(originalOutStream); System.setErr(originalErrStream); //You must close the streams which will auto flush them outPrintStream.close(); errPrintStream.close(); >> // end run() >); // end writing thread //Start the code that will write into streams writingThread.start(); String line; final List completeOutputStreamContent = new ArrayList(); while ((line = outReader.readLine()) != null) < completeOutputStreamContent.add(line); >// end reading output stream final List completeErrorStreamContent = new ArrayList(); while ((line = errReader.readLine()) != null) < completeErrorStreamContent.add(line); >// end reading output stream 

How to get a the output to a console as a string in java, I have already tried using a scanner but that is only for typing into the console and I read the documentation on pipes but from my understanding you still need to give the pipe data rather than the pipe getting it from the console. Does anyone know what I need to use to get the strings printed from the console?

How to store console output to text file using java?

If you’re running your Java program from the shell, you can redirect it’s output to a file using the ‘>’ operator.

EXAMPLE# java MyProgram.class > output.txt

Java: How to save console output to a text file?, Using this method you can pass you FileInputstream to System.setOut and you can save the console output. PrintStream printStream = new PrintStream (new FileOutputStream (file)); System.setOut (printStream); One interesting part of this question is though out is declared as final in System class …

Read the last console output and save it to a variable/string

The task is quite strange, but here’s quick-and-dirty solution:

import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.StringWriter; public class FilterOutput < static class MemorizingOutputStream extends FilterOutputStream < StringWriter sw = new StringWriter(); String last = null; public MemorizingOutputStream(OutputStream out) < super(out); >@Override public void write(int b) throws IOException < write(new byte[] , 0, 1); > @Override public void write(byte[] b) throws IOException < write(b, 0, b.length); >@Override public void write(byte[] b, int off, int len) throws IOException < out.write(b, off, len); String s = new String(b, off, len); int pos = s.lastIndexOf('\n'); if(pos == -1) < sw.append(s); >else < int pos2 = s.lastIndexOf('\n', pos-1); if(pos2 == -1) < sw.append(s.substring(0, pos)); last = sw.toString(); >else < last = s.substring(pos2+1, pos); >sw = new StringWriter(); sw.append(s.substring(pos+1)); > > public String getLast() < return last; >> public static void main(String[] args) < MemorizingOutputStream memOut = new MemorizingOutputStream(System.out); System.setOut(new PrintStream(memOut)); System.out.println("first"); System.out.println("second"); System.out.println("third"); System.err.println(memOut.getLast()); >> 

First it replaces the standard output stream with special stream which memorizes the last string (assuming that strings end with ‘\n’ ). Then you can query that stream for the last string which was printed. Note that this implementation is not thread-safe.

How could I read Java Console Output into a String buffer, Here is a utility Class named ConsoleOutputCapturer. It allows the output to go to the existing console however behind the scene keeps capturing the output text. You can control what to capture with the start/stop methods. In other words call start to start capturing the console output and once you are done …

Источник

Redirect Console Output to String in Java

If the function is printing to System.out , you can capture that output by using the System.setOut method to change System.out to go to a PrintStream provided by you. If you create a PrintStream connected to a ByteArrayOutputStream , then you can capture the output as a String .

// Create a stream to hold the output
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
// IMPORTANT: Save the old System.out!
PrintStream old = System.out;
// Tell Java to use your special stream
System.setOut(ps);
// Print some output: goes to your special stream
System.out.println("Foofoofoo!");
// Put things back
System.out.flush();
System.setOut(old);
// Show what happened
System.out.println("Here: " + baos.toString());

This program prints just one line:

System.out to string

Even if not the best idea, one solution could be:

public static void main(String[] xxx) System.setOut(new DoublePrintStream(System.out, "/myfile.txt")); 
System.setErr(new DoublePrintStream(System.err, "/errors.txt"));

System.out.println("this works");
try < throw new RuntimeException("oulala");>catch(Exception e) < e.printStackTrace(); >

//System.out.close(); // maybe required at the end of execution
>

class DoublePrintStream extends PrintStream private final OutputStream fos;

DoublePrintStream(OutputStream out, String filename) super(out);

try fos = new FileOutputStream(new File(filename));
> catch (FileNotFoundException e) throw new AssertionError("cant create file", e);
>
>

@Override
public void write(byte[] buf, int off, int len) super.write(buf, off, len);

try fos.write(buf, off, len);
> catch (IOException e) throw new RuntimeException(e);
>
>

@Override
public void close() try fos.close();
> catch (IOException e) throw new RuntimeException(e);
> finally super.close();
>
>
>

so you have output in the console + in a file, and all errors in a separate file.

Even if logging frameworks are way better, this solution has the advantage to require no code change at all.

PS: in a multithreaded context, you should also synchronize the methods of DoublePrintStream

How to capture all system.out.println to an array or list of string

System.out.println method has print and newLine methods. There is no way to capture only System.out.println method, you should capture all System.out.print methods with changing System.out variable.

System.out.println jdk implementation:

 public void println(String x) synchronized (this) print(x); 
newLine();
>
>

Text collector output stream class for capturing System.out.print content:

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class TextCollector extends OutputStream private final List lines = new ArrayList<>();
private StringBuilder buffer = new StringBuilder();

@Override
public void write(int b) throws IOException if (b == '\n') lines.add(buffer.toString());
buffer = new StringBuilder();
> else buffer.append((char) b);
>
>

public List getLines() return lines;
>
>

Example test implementation:

import java.util.*;
import java.io.*;

public class Main public static void main(String[] args) // store current output
PrintStream tmpOut = System.out;

// change stream into text collector
TextCollector textCollector = new TextCollector();
System.setOut(new PrintStream(textCollector));

// collect lines
System.out.println("Test-1");
System.out.println("Test-2");

// print lines to console
System.setOut(tmpOut);
List lines = textCollector.getLines();
for (String line : lines) System.out.println(line);
>
>
>

Redirect stdout to a string in Java

Yes — you can use a ByteArrayOutputStream :

ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));

Then you can get the string with baos.toString() .

To specify encoding (and not rely on the one defined by the platform), use the PrintStream(stream, autoFlush, encoding) constructor, and baos.toString(encoding)

If you want to revert back to the original stream, use:

System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));

Redirecting console output to GUI

You need to invoke startMeUp in a new thread, because your console program is blocking the event dispatch thread. Like this:

new Thread () @Override public void run () GreenhouseControls.startMeUp(); 
>
>.start();
GreenhouseControls.startMeUp();

I want to save eclipse console log into a string

You can redirect console output to file in run configuration settings on the «Common» tab.

Sample Image

Java/Kotlin way to redirect command output to both stdout and String

Here is the ProcessBuilder solution, which I initially wanted to avoid. It does the job though it is bulky. Let me know if a better API is made available!

var logs:String = ""
runCatching var command:List = listOf("command", "arg")
parameters.params?.let // dynamic args
ProcessBuilder(command)
.directory(File(scriptRoot))
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectErrorStream(true) // Merges stderr into stdout
.start().also < process ->
withContext(Dispatchers.IO) < // More info on this context switching : https://elizarov.medium.com/blocking-threads-suspending-coroutines-d33e11bf4761
launch process.inputStream.bufferedReader().run while (true) < // Breaks when readLine returns null
readLine()?.let < line ->
logger.trace(line) // realtime logging
logs += "$line\n" // record
> ?: break
>
>
>

process.waitFor(60, TimeUnit.MINUTES)
if(process.isAlive) logs += "TIMEOUT occurred".also < logger.warn(it) >+ "\n"
process.destroy()
>
>
>
>.onSuccess < process ->
if(process.exitValue() == 0) // completed with success
> else // completed with failure
>

>.onFailure < ex ->
logs = ex.stackTraceToString()
>

// Logs are available in $logs

Источник

Оцените статью