Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Console read input

Tags:

I'm just starting to learn Groovy and I am experimenting in GroovyConsole.

Is there a way I can read user input? I have tried the code below but I get an error.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in))  print "Input:"  input = br.readLine()  println "You entered: $input"

This is the error I am receiving:

Exception thrown 17-Apr-2012 02:52:39 org.codehaus.groovy.runtime.StackTraceUtils sanitize  WARNING: Sanitizing stacktrace:  java.io.IOException: Stream closed

Is there anything I need to import?

Any help would be great.

Thanks

like image 886
James Avatar asked Apr 17 '12 01:04

James


People also ask

How do I read a value in Groovy?

The get() method in the Groovy enhanced Map interface accepts two parameters. The first parameter is the name of the key we want to get a value for. And the second parameter is the default value if there is no value for the key.

How do I print results in Groovy script?

You can print the current value of a variable with the println function.


1 Answers

I got here trying to find out the easiest way to read user input from the command line... I found the answer elsewhere, will post here to document the 'real' Groovy way as it's still missing:

def username = System.console().readLine 'What is your name?' println "Hello $username" 

As Larry Battle says, if using the groovy console, make sure to look at the background 'black' window for the output and to type input.

EDIT

In an environment where Console is not available, such as running from your IDE, probably, use this instead:

println "What is your name?" println "Your name is ${System.in.newReader().readLine()}" 
like image 136
Renato Avatar answered Sep 20 '22 18:09

Renato