2011-02-24 9 views
13

मैं जावा में टेक्स्ट एरिया में कंसोल की सामग्री प्राप्त करने का प्रयास कर रहा हूं।जावा में कंसोल सामग्री को पाठ में रीडायरेक्ट करने के लिए कैसे करें?

उदाहरण के लिए अगर हम इस कोड है,

class FirstApp { 
    public static void main (String[] args){ 
     System.out.println("Hello World"); 
    } 
} 

और मैं उत्पादन एक पाठ क्षेत्र के लिए "नमस्ते दुनिया" करना चाहते हैं, क्या actionPerformed मैं चयन करने के लिए है?

+5

यह कमाल है! :) – Roman

उत्तर

1

आप एक कस्टम, PrintStream के प्रत्यक्ष उपवर्ग को System.out रीडायरेक्ट करने के लिए, ताकि प्रत्येक चार या लाइन है कि धारा को जोड़ा गया पाठ क्षेत्र की सामग्री को अद्यतन कर सकते हैं होगा (मुझे लगता है, यह एक AWT या स्विंग घटक है)

PrintStream उदाहरण एक ByteArrayOutputStream, जो पुनः निर्देशित System.out

2

तरीका में से एक के उत्पादन में आप एक PipedOutputStream को System OutputStream की स्थापना करके यह कर सकते हैं इकट्ठा करने और एक PipedInputStream है कि आप पढ़ने के लिए कनेक्ट कि होगा के साथ बनाया जा सकता है पाठ को अपने घटक में जोड़ने के लिए, उदाहरण

PipedOutputStream pOut = new PipedOutputStream(); 
System.setOut(new PrintStream(pOut)); 
PipedInputStream pIn = new PipedInputStream(pOut); 
BufferedReader reader = new BufferedReader(new InputStreamReader(pIn)); 

क्या आपने निम्न लिंक देखा है? यदि नहीं, तो आपको चाहिए।

8

Message Console इस के लिए एक समाधान को दर्शाता है।

+0

बहुत उपयोगी लिंक! –

+0

फिर भी, शुद्ध सोने। – gdbj

2

मैं इस सरल समाधान पाया:

public class CustomOutputStream extends OutputStream { 
    private JTextArea textArea; 

    public CustomOutputStream(JTextArea textArea) { 
     this.textArea = textArea; 
    } 

    @Override 
    public void write(int b) throws IOException { 
     // redirects data to the text area 
     textArea.append(String.valueOf((char)b)); 
     // scrolls the text area to the end of data 
     textArea.setCaretPosition(textArea.getDocument().getLength()); 
     // keeps the textArea up to date 
     textArea.update(textArea.getGraphics()); 
    } 
} 

तो फिर तुम मानकों का पालन के रूप में बदल देते हैं::

JTextArea textArea = new JTextArea(50, 10); 
PrintStream printStream = new PrintStream(new CustomOutputStream(textArea)); 
System.setOut(printStream); 
System.setErr(printStream); 

सबसे पहले, आप मानक आउटपुट को बदलने के लिए एक वर्ग बनाने के लिए समस्या यह है कि सभी आउटपुट केवल टेक्स्ट क्षेत्र में दिखाए जाएंगे।

नमूना के साथ स्रोत: http://www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea

+0

यह लगभग सही है, लेकिन जब भी कंसोल आउटपुट textarea एक गुच्छा flashed। संलग्न करने के बजाय, 'textArea.setText (textArea.getText() + String.valueOf ((char) paramInt) का उपयोग करें;) इसके बजाय, यह फ़्लैश नहीं है और मूल' System.out' की तरह बहती है। –

+0

इस काम के लिए आपको SwingUtilities.invokeLater() का उपयोग करना पड़ सकता है। –

संबंधित मुद्दे

 संबंधित मुद्दे