Java CommandLine cmd user input UI [duplicate] - java

This question already has an answer here:
is there any function in java which behaves like getopt from c
(1 answer)
Closed 5 years ago.
I am writing a java program that will be run from the command line and where the user should be able to indicate their preferences like this, for example:
The user wants to send from the Client to the Server their name (n) and weight (k), and they'll set the Server to have a window (w)of 4 and a delay (d) of 50%...so the commandline would look something like this:
(java abc.Client -n Roger -k 400 receiver_ip_addr receiver_port java
abc.Server -w 4 -d 0.5 receiver_ip_addr receiver_port)
Everything I look up on UI from the commandline mentions reading with Scanner, like: "what is your name?" followed by: name = Scanner.nextLine();
Thanks in advance for any help!

Check the description of the java main method:
https://docs.oracle.com/javase/tutorial/getStarted/application/index.html
The main method accepts a single argument: an array of elements of type String.
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information >to your application. For example:
java MyApp arg1 arg2
So you just need to iterate through the arguments and read them.

Related

Is there an easy way to execute an external java program from within a python script? [duplicate]

This question already has answers here:
How to call an external program in python and retrieve the output and return code?
(5 answers)
Closed 2 years ago.
I have a java program that i run with the following command
java -jar <program_name>.jar --<some_parameter> <some_filename>.csv
Within my python script I create the <some_filename>.csv. Then, I would like to execute the java program and use the program's stdout output in my python script.
Is there an easy way to do so?
Try with subprocess:
import subprocess
result = subprocess.run([COMMAND LIST], stdout=subprocess.PIPE)
print(result.stdout)
[COMMAND LIST] is a string list of the words in the command separated by space
Try with this:
import subprocess
p = subprocess.Popen(["java", "-jar <program_name>.jar --<some_parameter> <some_filename>.csv"],shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if not out:
print(err.rstrip().decode())
else:
print(out.rstrip().decode())

how to use windows default voice using java? [duplicate]

Is there a way to use the MS Speech utility from command line? I can do it on a mac, but can't find any reference to it on Windows XP.
My 2 cents on the topic, command line one-liners:
on Win using PowerShell.exe
PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('hello');"
on Win using mshta.exe
mshta vbscript:Execute("CreateObject(""SAPI.SpVoice"").Speak(""Hello"")(window.close)")
on OSX using say
say "hello"
Ubuntu Desktop (>=2015) using native spd-say
spd-say "hello"
on any other Linux
refer to How to text-to-speech output using command-line?
commandline function using google TTS (wget to mp3->mplayer)
command using google with mplayer directly:
/usr/bin/mplayer -ao alsa -really-quiet -noconsolecontrols "http://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&q=Hello%20World&tl=en";
on Raspberry Pi, Win, OSX (or any remote) using Node-Red
npm i node-red-contrib-sysmessage
There's a nice open source program that does what you're asking for on Windows called Peter's Text to Speech available here: http://jampal.sourceforge.net/ptts.html
It contains a binary called ptts.exe that will speak text from standard input, so you can run it like this:
echo hello there | ptts.exe
Alternatively, you could use the following three line VBS script to get similar basic TTS:
'say.vbs
set s = CreateObject("SAPI.SpVoice")
s.Speak Wscript.Arguments(0), 3
s.WaitUntilDone(1000)
And you could invoke that from the command line like this:
cscript say.vbs "hello there"
If you go the script route, you'll probably want to find some more extensive code examples with a variable timeout and error handling.
Hope it helps.
There's also Balabolka: http://www.cross-plus-a.com/bconsole.htm
It has a command line tool balcon.exe. You can use it like this:
List voices:
balcon.exe -l
Speak file:
balcon.exe -n "IVONA 2 Jennifer" -f file.txt
Speak from the command-line:
balcon.exe -n "IVONA 2 Jennifer" -t "hello there"
More command line options are available. I tried it on Ubuntu with SAPI5 installed in Wine. It works just fine.
If you can't find a command you can always wrap the System.Speech.Synthesis.SpeechSynthesizer from .Net 3.0 (Don't forget to reference "System.Speech")
using System.Speech.Synthesis;
namespace Talk
{
class Program
{
static void Main(string[] args)
{
using (var ss = new SpeechSynthesizer())
foreach (var toSay in args)
ss.Speak(toSay);
}
}
}
There is a powershell way also:
Create a file called speak.ps1
param([string]$inputText)
Add-Type –AssemblyName System.Speech
$synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
$synth.Speak($inputText);
Then you can call it
.\speak.ps1 "I'm sorry Dave, I'm afraid I can't do that"
rem The user decides what to convert here
:input
cls
echo Type in what you want the computer to say and then press the enter key.
echo.
set /p text=
rem Making the temp file
:num
set num=%random%
if exist temp%num%.vbs goto num
echo ' > "temp%num%.vbs"
echo set speech = Wscript.CreateObject("SAPI.spVoice") >> "temp%num%.vbs"
echo speech.speak "%text%" >> "temp%num%.vbs"
start temp%num%.vbs
pause
del temp%num%.vbs
goto input
pause
Your best approach is to write a small command line utility that will do it for you. It would not be a lot of work - just read text in and then use the ms tts library.
Another alternative is to use Cepstral. It comes with a nice command line utility and sounds light years better than the ms tts.

How can I pass variables from the command prompt into my java program

Is there a way to read data from the command prompt? I have a java program that relies on 4 input variables from an outside source. These variables are returned to the command prompt after I run a javascript program but i need a way to pass these variables from the command prompt into my java program, any help would be greatly appreciated!
While executing java program pass the parameters and all the parameters should be separated by space.
java programName parameter1 parameter2 parameter3 parameter4
This parameters would be available in your main method argument
public static void main(String[] args){
//This args array would be containing all four values, i.e. its length would be 4 and you easily iterate values.
for(int i=0; i<args.length; i++){
System.out.println("Argument " + i + " is " + args[i]);
}
Follow the link:
Command-Line Arguments - The Java™ Tutorials : https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
shared by #BackSlash.
It has all the content which would help you to clear all your doubts.
The content from the link is quoted below:
Displaying Command-Line Arguments passed by user from command-line to a Java program
The following example displays each of its command-line arguments on a
line by itself:
public class DisplayCommandLineParameters {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
To compile the program: From the Command Prompt, navigate to the directory containing your .java file, say C:\test, by typing the cd
command below.
C:\Users\username>cd c:\test
C:\test>
Assuming the file, say DisplayCommandLineParameters.java, is in the
current working directory, type the javac command below to compile it.
C:\test>javac DisplayCommandLineParameters.java
C:\test>
If everything went well, you should see no error messages.
To run the program: The following example shows how a user might run the class.
C:\test>java DisplayCommandLineParameters Hello Java World
Output:
Hello
Java
World
Note that the application displays each word — Hello, Java and World —
on a line by itself. This is because the space character separates
command-line arguments.
To have Hello, Java and World interpreted as a single argument, the
user would join them by enclosing them within quotation marks.
C:\test>java DisplayCommandLineParameters "Hello Java World"
Output: Hello Java World

Issue with Command Line arguments which got spaces in it

I have a Java program which I'm executing in a Linux environment through a bash script.
This is my simple bash script, which accepts a String.
#!/bin/bash
java -cp com.QuoteTester $1
The issue is that the command line argument can be with Spaces or Without spaces.
For example it can be either:
Apple Inc. 2013 Jul 05 395.00 Call
OR
Apple
My code is:
public static void main(String[] args)
{
String symbol = args[0];
if (symbol.trim().contains(" ")) // Option
{
}
else // Stock
{
}
}
So the issue is that , when I am trying to execute it this way:
./quotetester Apple Inc. 2013 Jul 05 395.00 Call
its only always going to the else condition that is Stock .
Is there anyway I can resolve this?
When you pass command line arguments with spaces, they are taken as space separated arguments, and are splitted on space. So, you don't actually have a single argument, but multiple arguments.
If you want to pass arguments with spaces, use quotes:
java classname "Apple Inc. 2013 Jul 05 395.00 Call"
This is not a Java issue per se. It's a shell issue, and applies to anything you invoke with such arguments. Your shell is splitting up the arguments and feeding them separately to the Java process.
You have to quote the arguments such that the shell doesn't split them up. e.g.
$ java -cp ... "Apple Inc. 2013"
etc.
See here for a longer discussion.
The arguments are handled by the shell , so any terminal settings should not affect this. You just need to have quoted argument and it should work.
Single quotes are the best option
Spaces and double quotes can be resolved this way.
java QuerySystem '((group = "infra") & (last-modified > "2 years ago"))'
In the original question the OP is using a shell script to call a java command line and would like the shell script to pass the arguments without performing the Blank interpretation (Word Splitting) option of input interpretation
https://rg1-teaching.mpi-inf.mpg.de/unixffb-ss98/quoting-guide.html#para:sh-ifs
If you know how many arguments there are then you can double quote the arguments
#!/bin/bash
java -cp com.QuoteTester "$1"
So you call this script, save as quotetester.sh.
./quotetester.sh "hello world"
and "hello world" gets passed as a single argument to Java. You could also use
./quotetester.sh hello\ world
with the same effect.

Is it possible to get the command used to launch the jvm in java?

I would like to know if it is possible to get from code the command used to launch a java program.
E.g. if I launch a java program with:
java -cp lib1:lib2:... -jar mylib.jar com.foo.Bar
I would like to get the exact string (jvm parameters included).
Is it possible?
Comment on the bounty and the question
Thank you all for your responses. Unfortunately, I did not get the answer I was initally looking for. I was hoping there was some portable solution to get the complete java command from within the program itself (including classpath etc.). As it seems there are no portable solution and since I am using Linux I am using the responses of agodinhost and Luigi R. Viggiano to solve my problem. However I give the bounty to rahulroc for the most complete (portable) response. For the rest an upvote for all :)
The below mentioned code should show all JVM parameters, arguments passed to the main method as well as the main class name.
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.List;
public static void main(String[] args) {
RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
List<String> jvmArgs = bean.getInputArguments();
for (int i = 0; i < jvmArgs.size(); i++) {
System.out.println( jvmArgs.get( i ) );
}
System.out.println(" -classpath " + System.getProperty("java.class.path"));
// print the non-JVM command line arguments
// print name of the main class with its arguments, like org.ClassName param1 param2
System.out.println(" " + System.getProperty("sun.java.command"));
}
javadoc for getInputArguments
Returns the input arguments passed to the Java virtual machine which
does not include the arguments to the main method. This method returns
an empty list if there is no input argument to the Java virtual
machine.
Some Java virtual machine implementations may take input arguments
from multiple different sources: for examples, arguments passed from
the application that launches the Java virtual machine such as the
'java' command, environment variables, configuration files, etc.
Typically, not all command-line options to the 'java' command are
passed to the Java virtual machine. Thus, the returned input arguments
may not include all command-line options.
You can also take a look at : jps
It's a Java program that is able to get the full command line for all
Java processes, including full class name of main class and JVM
options.
You can find a good summary of various JVM tools, including
Java Application Launcher links to :
ManagementFactory.getRuntimeMXBean() - Returns the managed bean for the runtime system of the Java virtual machine.
getInputArguments() javadoc
determine if JVM is running in debug mode
You can use this to retrieve the VM parameters :
public static void main(String args[]) {
List<String> inputArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
System.out.println("input arguments = " + inputArguments);
}
However it won't give you all the command line (only gives the JVM arguments, no main class nor parameters). Sample output:
input arguments = [-Dfile.encoding=UTF-8, -XX:-UseTLAB, -Xms2000m, -Xmx2000m, -XX:+PrintCompilation, -XX:+PrintGC]
It only works on Sun Oracle JVM: System.getProperty("sun.java.command")
Additionally, you can have a look at JavaSysMon, it can report command line of active processes. To check which is the current JVM Process check here: How can a Java program get its own process ID?
in a linux machine would be easier to run:
ps -ef | grep java
this command will list all java programs running with it's used parameters.
Not sure about what can be used in a windows environment.
In the task manager on Win2003 you can enable the display of a column that displays the command like it does on linux. Or, you can do it from the command line like so:
wmic.exe PROCESS where "name like '%java%'" get Processid,Caption,Commandline

Categories

Resources