Redirect, System.out ?
Hi.
I want to redirect System.out to a Swing Component like JTextArea, etc.
try with printstream, Reader, etc. but i dont know how.!.
I want to see, messages (The standard out) in a Swing Component.
plis some help..
tnks.
I was using the Redirect method you made edna for my software and it works wonderfully when using strings, unfortunately I ran in to a strange problem which is fitting since my current objective is very strange.
I am writing a piece of software that has an embedded jython interpreter in it. When I execute my jython scripts all the output went to the console and I had no direct way of saying append to this particular text area since I wasn't able to pass my Java GUI class in to the script.
Thus redirecting my output with your method came in quite handy. This is where the problem comes in. I tried the println function in my regular java classes and all the primitive types worked fine, but within in the script only String worked. Here is the code for the println function
PrintStream stdout = new PrintStream(System.out) {
public void println(String x) {
outputTextArea.append(x + "\n");
public void println(int x) {
outputTextArea.append(x + "\n");
public void println(boolean x) {
outputTextArea.append(x + "\n");
public void println(Object x) {
outputTextArea.append(x.toString() + '\n');
};Here is the sample Jython code:
import JythonScripter
System.out.println(4) #fails to print correctly
System.out.println("HelloWorld") #works
System.out.println(10) #fails
System.out.println("Goodbye Cruel World") #works
If you have any advice on why strings would work but not other types I would greatly appreciate it.
Similar Messages
-
Redirecting System.out() output to a JTextArea control
I want to be able to redirect System.out() and System.err() messages to a JTextArea control:
I know how to redirect output to a file as follows:
FileOutputStream fos =
new FileOutputStream(filename, true);
PrintStream ps = new PrintStream(fos, true);
System.setOut(ps);
System.setErr(ps);
How can I set it up so that I can recognise when messages have been to System.out() with a view to displaying the message within the JTextArea?
I guess I need to set it up so that the JTextArea control acts as an Observer. The bit I'm having difficulty with is figuring out how I can automatically determine when information has been written to System.out()?
Hopefully I'm explaining my issue in enough detail and clarity.
thanks
- GarryI would suggest you set up a separate thread to monitor System.out. Use a PipedOutputStream and redirect System.out to that, then connect that to a PipedInputStream that your other thread is continually waiting to read. Each time that thread reads a line, it should append the line to the JTextArea, using SwingUtilities.invokeLater.
This is just a rough outline of something that might work. Hope it helps. -
Redirecting System.out to a textfield
I want the output created by System.out (especially error messages) redirected to a textfield in stead of the console. How can I do this?
this is how I've done it. Just create a new instance of this class and pass in your TextArea. It redirects System.out and checks for messages on System.out every 5 seconds.
import java.io.*;
import javax.swing.*;
public class TextOut
implements Runnable
private JTextArea text;
private Reader in;
private Thread t;
public TextOut( JTextArea text )
throws Exception
this.text = text;
PipedOutputStream pout = new PipedOutputStream();
System.setOut( new PrintStream( pout ) );
in = new InputStreamReader( new PipedInputStream( pout ) );
t = new Thread( this );
t.start();
public void run()
while( true )
try
StringBuffer buffer = null;
while( in.ready() )
if ( buffer == null ) buffer = new StringBuffer();
buffer.append( (char)in.read() );
if ( buffer != null )
text.append( buffer.toString() );
java.awt.Rectangle r = new java.awt.Rectangle();
text.computeVisibleRect( r );
text.repaint( r );
t.sleep( 5000 );
} catch (IOException ioe) {
text.append( "" + ioe );
} catch (InterruptedException ie ) {
text.append( "" + ie ); -
Redirecting System.out?
I am working with a team, and I am testing a standalone Java application using separate unit tests. The program takes text input and outputs some text results, but the way it is set up, it will output directly to System.out as soon as it needs it. I am not in control of the way it outputs the results.
I need to capture all of the results from System.out, and compare them to what I know should be printed out. How do I do this without touching the original source files? Is there a way to do it purely in Java (my backup is to use shell scripts, but I really don't want to)?Well, you don't need to change all the source files, but you will need to
change the source file with your main method.You don't even have to do that: build a Wrapper class with its own main
that redirects System.out to a file and calls the Application.main afterwards.
Instead of starting the Application, start the Wrapper.
kind regards,
Jos -
Redirect system.out.println() to a file
hi all,
how can i redirect all the console prints to a txt file in java application? i have used system.out oftenly in many class throught the
application. is there any way to redirect all those console prints to a
txt file by converting or assigning the System.out stream to a stream for filewriter or
somthing like that, so that whenever system.out.println() is executed
the content is written to a file insted of on the console.
thanks in advance
SojanActually,System.setOut(new PrintStream(new FileOutputStream("output.txt"), true));
System.setErr(System.out);since setOut wants a PrintStream and not just some OuputStream... -
Redirecting System.out to a JTextArea
How can I redirect the System.out Stream into a JTextArea?
I found the method System.setOut(PrintStream out) but I don't know
how to get the PrintStream of my TextArea.I don't know if this is the most efficient way but it provides an example of using Pipes:
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TextAreaStream extends JTextArea implements Runnable{
private static final PipedOutputStream _pipeOut = new PipedOutputStream();
static{
System.setOut( new PrintStream(_pipeOut) );
private InputStream _pipeIn;
private byte[] buffer = new byte[256];
public TextAreaStream(){
this(1,10);
public TextAreaStream(int numRows, int numCols){
super(numRows, numCols);
Thread t = new Thread(this);
t.setDaemon(true);
t.start();
try{
pipeIn = new BufferedInputStream(new PipedInputStream(pipeOut));
catch(IOException e){
System.err.println("Error creating pipe: "+e);
public void run(){
while(true){
try{
//blocks at read
int bytesRead = _pipeIn.read(buffer);
append(new String(buffer,0,bytesRead));
catch(IOException e){
System.err.println(e);
public static void main(String[] args){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea text = new TextAreaStream();
text.setBorder(BorderFactory.createTitledBorder("System.out"));
f.getContentPane().add(text);
//Add an input component
JPanel north = new JPanel(new FlowLayout(FlowLayout.LEFT));
final JTextField field = new JTextField(25);
north.add(field);
north.add(new JLabel("Add text, press Enter"));
f.getContentPane().add(north, BorderLayout.NORTH);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(field.getText());
field.setText("");
f.setSize(600, 400);
f.show();
} -
Redirecting System.out/err
Hi all,
Is there an easy way to redirect the System.out/err stream to my own stream? I want to implement that everything going to System.out/err will be printed in a JTextArea instead of the console (Like JBuilder does for example).
Thanks for any hint, MathiasSystem.setErr(myErrorOutputStream);
System.setOut(myStdOutStream); -
Redirecting system.out to a file
I want to have the output of these threads go to a file, which it is doing now, but the program is finishing before all the data is written to the file.
I had another idea that the threads could write to a shared stringbuffer and then when they have finished, i could write the contents of that stringbuffer to a file, but when do it tell it to write to the file. how can i tell when the threads are finished.
/* 12 Nov 2002
Class extends PThread which extends Thread.
import Concurrency.*;
import java.io.*; //added to write output to a file
public class Exercise1 extends PThread{
private static File theOutputFile;
private static FileWriter fileWriterStream;
private static int counter = 0;
public Exercise1() {
try {
if(theOutputFile == null) {
theOutputFile = new File("output.txt");
fileWriterStream = new FileWriter(theOutputFile);
}catch(IOException ioe){}
public static void main(String[] args) throws IOException {
System.out.println("Dave Casserly\n" +
"Check the source folder for a file called output.txt\n" +
"This contains the programs output.\n");
Exercise1 thread1 = new Exercise1();
Exercise1 thread2 = new Exercise1();
thread1.start();
thread2.start();
//each thread will look at counter make sure its less than 1000,
//get the current counter value and increment it
//print it to screen
//then increment the static counter
public void run(){
try {
while(counter <= 1000) {
int count = counter;
count++;
counter++;
System.out.println("COUNT = " + count); //write to screen
fileWriterStream.write("COUNT = " + count + "\n"); //write to file
counter = count;
}catch(IOException io){}
}//end of classYou need to join the main thread with the child threads.
Something like this:
Exercise1 thread1 = new Exercise1();
Exercise1 thread2 = new Exercise1();
thread1.start();
thread2.start();
thread2.join();
thread1.join();Or something. -
Is it possible to redirect System.out and System.in for a thread
I would like to run two threads. One should keep writing to System.out and System.in. The other thread output written to System.out and System.in shoudl be captured and written to a file. Is this possible? I don't think so, but perhaps someone know some workaround.
raspedhmmm sure it's possible. You can write an outputstream that does different things depending on which thread is running, and then set system.out to a printstream that writes to that outputstream.
-
Urgent: Redirecting System.out.println to more than one place
Hi All,
I want to divert all my System.out.println() statements to a Log file as well as on to the screen.
But only one of the 2 options actually works.
So if anyone can suggest me some ways I will appreciate very much.
My code looks something like this:-
if (m_filename != null) {
try {
FileOutputStream fos = new FileOutputStream(m_filename);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.setErr(ps);
//This code Added for Printing Onto Screen But it does not work
Stream ps1 = new PrintStream(System.out);
System.setOut(ps1);
System.setErr(ps1);
} catch (IOException ioe) {
System.out.println("Could not create log file " + m_filename + " because " + ioe);
As far as logging onto file is menat it works when i set it but printing onto screen does not.
How can i achive it
Thanks
RajHi,
You are right but in my current scenario i cannot incorporate this log4j because my application is using some other framework and I am just trying to override this frameworks loggig behaviour so that it logs to both a log file as well as on to the screen.
Here is the code that this framework uses for logging and i am simply overriding it to do the reqd thing but its not working for me:-
* Resets the System's out and err OutputStreams to the Launcher's
* own ThreadedOutputStream, so that output from different threads
* can be tracked efficiently.
protected void setOutputStreams() {
if (scInfo.size() <= 1) {
// don't need Threaded handling with one thread
if (m_filename != null) {
try {
FileOutputStream fos = new FileOutputStream(m_filename);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.setErr(ps);
//Added for Printing Onto Screen
PrintStream ps1 = new PrintStream(System.out);
System.setOut(ps1);
System.setErr(ps1);
} catch (IOException ioe) {
Debug.fatalError("Launcher.setOutputStreams","Could not create log file " + m_filename + " because " + ioe);
else {
Debug.information("Launcher.setOutputStreams","Initializing ThreadedPrintStream");
if (m_filename == null) {
System.setOut(new ThreadedPrintStream(System.out));
System.setErr(new ThreadedPrintStream(System.err));
else {
PrintStream out = new ThreadedPrintStream(m_filename);
System.setOut(out);
System.setErr(out);
//Added for Printing Onto Screen
System.setOut(new ThreadedPrintStream(System.out));
System.setErr(new ThreadedPrintStream(System.err));
Debug.information("Launcher.setOutputStreams","ThreadedPrintStream initialized.");
Thanks
Raj -
Redirecting System.out and System.err to files
Is there a way I can configure my web-appliction (in web.xml or something) to redirect all the output (.err and .out) to specific files?
I think you could create PrinStreamS from your desired output files and then use System.setOut(<...>) and System.setErr(<...>). Place this code in a servlet that you load at startup...
-
Redirecting System.out stream to a TextArea
I hope this isn't a stupid question--I'm blanking pretty hard.
I want to use System.setOut() to direct standard output to a TextArea within a Frame. Is there a way to setup a TextArea to receive text from an output stream, or is an intermediary of some sort necessary?
I feel like this is pretty easy, but I'm stumbling. That's what I get for doing J2EE for a year rather than GUI. :P
Any input is appreciated!Here's the compiled and tested code...I learned some good stuff from this link as to why my simpler approach didn't work:
http://www.devx.com/upload/registered/features/javapro/1999/11nov99/tl1199/tl1199.asp
Here is my code:
class OutRouter implements Runnable
PipedInputStream pipeIn = null;
JTextArea textArea = null;
OutRouter( JTextArea ta, PipedOutputStream pos)
try
pipeIn = new PipedInputStream(pos);
catch(IOException ioe)
ioe.printStackTrace(System.err);
System.exit(1);
textArea = ta;
public void run()
String line = null;
BufferedReader pipeReader = new BufferedReader(
new InputStreamReader(pipeIn));
try
while(true)
Thread.sleep(100);
if(pipeIn.available() == 0)
continue;
line = pipeReader.readLine();
if(line == null)
continue;
System.err.println("Line = " + line);
final String fLine = line;
SwingUtilities.invokeAndWait( new Runnable()
{public void run()
{ textArea.append(fLine + "\n"); }
catch(InvocationTargetException ite)
{ ite.printStackTrace(System.err); System.exit(1); }
catch(InterruptedException ie)
{ ie.printStackTrace(System.err); System.exit(1); }
catch(IOException ioe)
{ ioe.printStackTrace(System.err); System.exit(1); }
} -
To redirect System.out stream output on swing's JTextArea
Following is a program that needs to print output as follows:-
EXPECTED OUTPUT ON GUI:_ In action block (datapayload value) In Routing block (argus value)
PRESENT PROGRAM OUTPUT ON GUI_ In action block (datapayload value)
please examine the below code and correct mistakes to get the expected output as given above.....
I am not getting the second line as output on GUI i.e., In Routing block (argus value)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Demo extends JFrame implements ActionListener
JTextField datapayload;
JLabel Datapayload;
JButton submit;
JTextArea textFieldName;
public Demo()
DemoLayout customLayout = new DemoLayout();
getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
getContentPane().setLayout(customLayout);
Datapayload = new JLabel("Enter DataPayload:");
getContentPane().add(Datapayload);
datapayload = new JTextField("abcd...");
getContentPane().add(datapayload);
submit = new JButton("submit");
getContentPane().add(submit);
textFieldName = new JTextArea(80,10);
textFieldName.setEditable( false );
JScrollPane scroll = new JScrollPane(textFieldName) ;
scroll.setBounds( 10, 60, 225, 150 );
getContentPane().add( scroll );
submit.addActionListener(this);
setSize(getPreferredSize());
public void actionPerformed(ActionEvent e)
String demodata=datapayload.getText();
textFieldName.append("In Action Block"+"\t"+demodata);
Demo pr = new Demo();
pr.DemoRoute(demodata);
public void DemoRoute(String argus)
textFieldName.append("In routing block"+"\t"+argus);
public static void main(String args[])
Demo window = new Demo();
window.setTitle("Demo");
window.pack();
window.show();
class DemoLayout implements LayoutManager
public DemoLayout() { }
public void addLayoutComponent(String name, Component comp) { }
public void removeLayoutComponent(Component comp) { }
public Dimension preferredLayoutSize(Container parent)
Dimension dim = new Dimension(0, 0);
Insets insets = parent.getInsets();
dim.width = 320 + insets.left + insets.right;
dim.height = 240 + insets.top + insets.bottom;
return dim;
public Dimension minimumLayoutSize(Container parent)
Dimension dim = new Dimension(0, 0);
return dim;
public void layoutContainer(Container parent)
Insets insets = parent.getInsets();
Component c;
c = parent.getComponent(0);
if (c.isVisible()) {c.setBounds(insets.left+90,insets.top+8,172,26);}
c = parent.getComponent(1);
if (c.isVisible()) {c.setBounds(insets.left+230,insets.top+8,172,26);}
c = parent.getComponent(2);
if (c.isVisible()) {c.setBounds(insets.left+230,insets.top+52,142,26);}
c = parent.getComponent(3);
if (c.isVisible()) {c.setBounds(insets.left+90,insets.top+100,472,268);}
} Edited by: 997189 on Mar 31, 2013 8:52 AMHi,
change your actionPerformed() method as below to get the required output.
public void actionPerformed(ActionEvent e)
String demodata=datapayload.getText();
textFieldName.append("In Action Block"+"\t"+demodata);
//Demo pr = new Demo(); You are creating a new object to all DemoRoute method. This is the problem
//pr.DemoRoute(demodata);
this.DemoRoute(demodata);
}And also my suggestion is follow java coding conventions while coding -
System.out Problem in Java Plug-in
I have the following problem, anyone can help me?
I have an application( Frame ) needed to be embedded in applet. The applecation has a lot of information output to console( by System.out ). When I embeded it into applet, these information will be output to Java Plug-in Console. In the beginning, there is no problem. But when the applet runs enough time, the output will be more and more, and the speed of the applet( in fact, the browser ) runs slower and slower.
I don't want to modify my application at all( it is impossible ). I wonder there is any good suggestion to this problem, I guess, maybe there is an interface to make the Java Plug-in clear its console buffer periodically.
Thanks in advance.There is a good reason for this.... the console in the java plug-in is essentially a JTextArea... and continually adding text to it via System.out.println or the like will make it slower the longer it runs..... periodically clearing the console would be the only solution without modifying the code......
If you still need all that information you could redirect System.out to your own PrintStream and then instead of writing to the console little by little, you could save the original System.out (using something like:
PrintStream origSysOut=System.out;
) and then later on in your app reset System.out=myPrintStream or something.... then just write the myPrintStream data to origSysOut every now and then or something....
if you want a better example of this I've got a log facility class that I built based on this principal... it's also and easy way to capture stack traces into log files... and since you're just redirecting System.out or err it's easy to turn off the log file to use for debugging.... ok that's enough of a rant :) -
How to make add the program system.out messages to a applet text field?
How to make add the program system.out messages to a applet text field?
System.out.println("I wanna displany this message on a applet text field, thanks");You may wish to change the output destination to a JTextArea. Please have a look at this link that likely shows what you want:
[http://forums.sun.com/thread.jspa?forumID=54&threadID=640376|http://forums.sun.com/thread.jspa?forumID=54&threadID=640376]
If you need other examples, search the forum. I found the search terms -- redirect system out textarea -- very helpful.
Good luck
Maybe you are looking for
-
XSL-FO for Standard Purchase Order, doesn't print page number
Hi, I worked on XSL-FO code to custom the PDF output for Standard PO. Everything works great: I added company logo (in a different position of the standard commented code <!-- Too easy just to uncomment... :-)--> ), i created new attribute sets to hi
-
Screen issues - not the glass but the screen underneath the glass
weird - screen under glass is pixelated - hard to describ but the GLASS IS NOT scratched - but screen is f'ed up - what option sdo I have to fix this
-
Nikon D610, RAW wird in Photoshop CC noch nicht unterstützt, was kann ich tun?
Nikon D610 : in Photoshop CC kann kein RAW gelesen werden, was kann ich tun?
-
PROBLEMS opening PDF in IE 9 or X
How can it be that Adobe releases a new version not able to open a PDF from a link? ADOBE GET IT FIXED!!!!!!! It can not be true that you have to change the settings in preferences before it works. How do I explain this to 1000 of my costumers?
-
Change width of splitter container and single container
Hi, im using a splitter container (abap oo style without dnpro elements) with 2 single containers. create object go_splitter exporting parent = go_docking rows = 1 columns = 2 Column 1 leftside =