How to get console data after printing it in java?

Viewed 64

I am working on java project where i need to get data from console. Following are my code and output case.

 public static void main(String[] args) {       
    String test= "Hii test";
    System.out.println(test);
}

Now in this program the output will be print "Hii test" now I want to get this data from console without using test variable. Please suggest how I get this data from console?

2 Answers

Getting data from the console isn't practical. Typically the console isn't considered an input medium. It would be best to grab the data before you output the data to the console into a variable, print it to the console, and then use it.

String test= "Hii test";
String newVariable = test;
System.out.println(test);
// use newVariable however you wish to use it.

Of course, my example is very simplistic however, I think you get the idea. you typically don't get data from the console.

You can proxy the output stream like so:

public static void main(String[] args) {

    final StringBuilder consoleData = new StringBuilder();

    final OutputStream proxyStream = new OutputStream() {
        final PrintStream originalStream = System.out;

        @Override
        public void write(int b) {
            consoleData.append((char) b);
            originalStream.write(b);
        }
    };

    System.setOut(new PrintStream(proxyStream, true));

    System.out.println("Some text");
    System.out.println(consoleData);
}

The output:

Some text
Some text
Related