2012-05-25 20 views
0

我想知道是否有采取方式String - 讓我們說:是否可以取一個字符串並將其放入System.in中?

String str = "blabla"; 

做:

System.in.setText(str); 

我知道這不工作 - 我想知道是否有一種方法來做到這一點。然後發送相同的字符串。就好像你會在控制檯上輸入並按輸入

這是一個帶有服務器套接字的程序,我試圖通過端口發送String,以便其他應用程序知道如何處理它。

編輯: 我找到了一種方法InputStream的重定向到一個文本框,當用戶在發送過來的System.in文本字段寫入。

import java.io.*; 
import javax.swing.*; 
import javax.swing.event.DocumentEvent; 
import javax.swing.event.DocumentListener; 

public class TextfieldInputStream extends InputStream implements DocumentListener { 

    private JTextField tf; 
    private String str = null; 
    private int pos = 0; 

    public TextfieldInputStream(JTextField jtf) { 
     tf = jtf; 
    } 

    @Override 
    public int read() { 
     //test if the available input has reached its end 
     //and the EOS should be returned 
     if(str != null && pos == str.length()){ 
      str = null; 
      //this is supposed to return -1 on "end of stream" 
      //but I'm having a hard time locating the constant 
      return java.io.StreamTokenizer.TT_EOF; 
     } 
     //no input available, block until more is available because that's 
     //the behavior specified in the Javadocs 
     while (str == null || pos >= str.length()) { 
      try { 
       //according to the docs read() should block until new input is available 
       synchronized (this) { 
        this.wait(); 
       } 
      } catch (InterruptedException ex) { 
       ex.printStackTrace(); 
      } 
     } 
     //read an additional character, return it and increment the index 
     return str.charAt(pos++); 
    } 

    public void changedUpdate(DocumentEvent e) { 
     // TODO Auto-generated method stub 
    } 

    public void insertUpdate(DocumentEvent e){ 
     str = tf.getText() + "\n"; 
     pos = 0; 
     synchronized (this) { 
      //maybe this should only notify() as multiple threads may 
      //be waiting for input and they would now race for input 
      this.notifyAll(); 
     } 
    } 

    public void removeUpdate(DocumentEvent e){ 
     // TODO Auto-generated method stub 
    } 
} 
+0

以及它的程序與服務器套接字,我試圖通過端口發送一個字符串。以便其他應用程序知道如何處理它 – Alex

+1

我很困惑,如果您嘗試通過端口發送字符串,您不應該使用Socket而不是System.in? – jtahlborn

+0

@jtahlborn很棒的評論。我是'編碼(原始)規範',但提及端口使得它可能是一個完全不同的問題和方法。 –

回答

4
package test.t100.t007; 

import java.io.ByteArrayInputStream; 
import java.util.Scanner; 

public class SystemIn { 

    public static void main(String[] args) { 
     String str = "blabla"; 
     ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes()); 
     System.setIn(bais); 
     // We might use the ByteArrayInputStream here, but going with System.in.. 
     Scanner scanner = new Scanner(System.in); 
     String input = scanner.next(); 
     System.out.println(input); 
    } 
} 
3

您可以使用PipedInputStream/PipedOutputStream對。然後,您可以使用System.setIn()方法將PipedInputStream設置爲System.in。最後,您可以寫入您的PipedOutputStream,並在System.in中提供結果。

相關問題