2009-10-07 25 views
13

मुझे आश्चर्य है कि क्या कोई तरीका है कि मैं अपने जावा कोड से निष्पादित कर रहे ग्रोवी स्क्रिप्ट के लिए डिफ़ॉल्ट आउटपुट (System.out) बदल सकता हूं।ग्रोवी स्क्रिप्ट से आउटपुट को रीडायरेक्ट कैसे करें?

public void exec(File file, OutputStream output) throws Exception { 
    GroovyShell shell = new GroovyShell(); 
    shell.evaluate(file); 
} 

और नमूना ग्रूवी स्क्रिप्ट:

यहाँ जावा कोड है

def name='World' 
println "Hello $name!" 

वर्तमान में विधि का निष्पादन, स्क्रिप्ट लिखते का मूल्यांकन करता है "नमस्ते दुनिया!" कंसोल (System.out) के लिए। मैं पैरामीटर के रूप में आउटपुटस्ट्रीम को आउटपुट पर रीडायरेक्ट कैसे कर सकता हूं?

उत्तर

16

Binding

public void exec(File file, OutputStream output) throws Exception { 
    Binding binding = new Binding() 
    binding.setProperty("out", output) 
    GroovyShell shell = new GroovyShell(binding); 
    shell.evaluate(file); 
} 

का उपयोग कर टिप्पणी के बाद इस प्रयास करें

public void exec(File file, OutputStream output) throws Exception { 
    Binding binding = new Binding() 
    binding.setProperty("out", new PrintStream(output)) 
    GroovyShell shell = new GroovyShell(binding); 
    shell.evaluate(file); 
} 

ग्रूवी स्क्रिप्ट

def name='World' 
out << "Hello $name!" 
+2

यह काम करेगा, लेकिन मैं मानक आउटपुट में लिखे गए किसी भी * आउटपुट को रीडायरेक्ट करना चाहता हूं। खासकर अंतर्निहित कार्यों जैसे हमें println()। –

+0

आप * के बारे में * सही थे। समाधान java.io.PrintStream आउटपुट int को लपेटना है और खोल के लिए "बाहर" संपत्ति के रूप में पास करना है! –

+0

हाँ !, मेरा पहला कांस्य बैज! हैप्पी यह काम करता है! आपने आउटपुट को कैसे लपेट लिया? – jjchiw

0

http://java.sun.com/j2se/1.3/docs/api/java/lang/System.html#setOut%28java.io.PrintStream%29 तुम सिर्फ क्या जरूरत है।

+0

मुझे डर है सिस्टम.सेटऑट बहुत हेवीवेट है :) यह पूरे जेवीएम के लिए वैश्विक रूप से आउटपुट को बदलता है और यह ऐसा कुछ नहीं है जिसे मैं करना चाहता था :) –

2

मुझे संदेह है कि आप अपने ग्रोवीशेल के मेटा क्लास में println विधि को ओवरराइट करके इसे काफी अच्छी तरह से कर सकते हैं। ग्रूवी कंसोल में निम्नलिखित काम करता है:

StringBuilder b = new StringBuilder() 

this.metaClass.println = { 
    b.append(it) 
    System.out.println it 
} 

println "Hello, world!" 
System.out.println b.toString() 

उत्पादन:

Hello, world! 
Hello, world! 
2

उपयोग SystemOutputInterceptor वर्ग। आप स्क्रिप्ट मूल्यांकन से पहले आउटपुट को रोकना शुरू कर सकते हैं और बाद में रुक सकते हैं।

def output = ""; 
def interceptor = new SystemOutputInterceptor({ output += it; false}); 
interceptor.start() 
println("Hello") 
interceptor.stop() 
2

javax.script.ScriptEngine का उपयोग करने के बारे में कैसे? आप इसके लेखक को निर्दिष्ट कर सकते हैं।

ScriptEngine engine = new ScriptEngineManager().getEngineByName("Groovy"); 
PrintWriter writer = new PrintWriter(new StringWriter()); 
engine.getContext().setWriter(writer); 
engine.getContext().setErrorWriter(writer); 
engine.eval("println 'HELLO'") 
संबंधित मुद्दे

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