I have a jar file which asks user the value of n. And adds the values entered. When the jar is executed from cmd.exe, works well. But when invoked from .bat file, it is not prompting for the input rather executes the further statements. I tried using pipe,as,
(echo 3
echo 10
echo 20
echo 30)| java -jar add.jar
but didn't work.How can I automate the input?
Note: values are not accepted as arguments, but as a prompt.
Without knowing something about the code it's hard to tell why it's not working for you.
See below a simple working example
Add.java
import java.util.Scanner;
public class Add {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (scanner.hasNextInt()) {
int value = scanner.nextInt();
sum += value;
System.out.println("sum = " + sum);
}
}
}
run.bat
#echo off
(echo 2
echo 10
echo 20
echo 30
echo end ) | java -jar Add.jar
compile and build the jar
javac Add.java
echo Main-Class: Add > manifest.mf
jar cmf manifest.mf Add.jar Add.class
run the batch file
run.bat
output
sum = 2
sum = 12
sum = 32
sum = 62
Related
I have a requirement where I need to execute 15 to 20 java programs parallely in the background. We can use nohup command and execute it directly but I want to execute this nohup command from another java program. I did some research on it and created a java program. but this below java program is working when I use java command, but if I use nohup then its failing
public static void main(String[] args) throws Exception {
String sourceFileName = args[0];
String targetFileName = args[1];
String type = args[2];
String logFileName = args[3];
Integer count = new Integer(args[4]);
// Below command is working
String command = "java -cp \"test-jar.jar\" com.test.MyTestClass ";
// Below command is not working
// String command = "nohup java -cp \"test-jar.jar\" com.test.MyTestClass ";
for(int i=1; i<=count; i++){
String cmd = command+sourceFileName+"_"+i+" "+targetFileName+"_"+i+" "+type+" 2>>"+logFileName+"_"+i+".log &";
runProcess(cmd);
}
}
private static void runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
pro.waitFor();
System.out.println(command + " exitValue() " + pro.exitValue());
}
For testing purpose I have taken the count as 3, If I use nohup command getting below output
nohup java -cp "test-jar.jar" com.test.MyTestClass source-file_1 target-file_1 TEST 2>>log-file_1.log & exitValue() 1
nohup java -cp "test-jar.jar" com.test.MyTestClass source-file_2 target-file_2 TEST 2>>log-file_2.log & exitValue() 1
nohup java -cp "test-jar.jar" com.test.MyTestClass source-file_3 target-file_3 TEST 2>>log-file_3.log & exitValue() 1
I kept the test-jar.jar in the same path from where I am executing this program.
Issue is because of 2 separate projects.
My class is in my-test project and the class which I want to execute is in test-jar project. I added test-jar dependency in 'my-test' project. Still faced the same issue. I added/copied My class in the test-jar file then I executed it. Now its working for both java and nohup commands
I have the following java class and a batch file.
testc.java:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Map;
public class testc {
public static void main(String[] mainargs) {
System.out.println("Java class initiated");
try {
String line;
ArrayList<String> args = new ArrayList<String>();
String script = "script-util.bat";
args.add(script);
ProcessBuilder pb = new ProcessBuilder(args);
Map<String, String> env = pb.environment();
System.out.println("Starting batch file");
Process process = pb.start();
InputStream is = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
while (null != (line = reader.readLine())) {
System.out.println("OUT: " + line);
}
System.out.println("Waiting for complete exit");
int returnCodeW = process.waitFor();
int returnCodeE = process.exitValue();
System.out.println("returnCodeW: " + returnCodeW);
System.out.println("returnCodeE: " + returnCodeE);
}
catch (Throwable t) {
System.out.println("Exception caught");
}
}
}
content of script-util.bat is just one line,
case 1:
exit /B 0
case 2:
exit /B 2
case 3:
exit 0
case 4:
exit 2
case 5:
rem exit 0
Output for "java testc" with batch file having content from case 1 when run in a non-evevated command prompt:
c:\javatest2>java testc
Java class initiated
Starting batch file
OUT:
OUT: c:\javatest2>exit /B 0
Waiting for complete exit
returnCodeW: 1
returnCodeE: 1
Output for case 5 returns code 1 instead of 0 too.
Output for any other cases, or all cases when run from the same working directory in an elevated command prompt reflects correct errorlevel code.
My question is why exit code returns 1 instead of 0 if not run as admin?
Environment:
Windows Server 2016 x64, JDK 1.8
Edit: This issue seems to be environment specific. One installation of Windows Server 2016 10.0.14393 using JDK 1.8 u151 behaves as above while another one of the same builds does not. Anyway this is not expected under any environment.
In cooperation with the customer we found out the cause.
The system was using a shell script to put different color to cmd window if the user opening it has administrative rights at that time. The command causing exit code to change is included in a custom script shell_color.cmd:
#echo off
rem The following line is the root cause
bcdedit 1>NUL 2>&1
rem bcdedit returns exit code 1 for some reason when run as non-admin
if %errorlevel%==1 goto user
color 4f
goto end
:user
color 0f
:end
and Windows registry needs this script to be referenced in the following way:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"autorun"="%windir%\\system32\\shell_color.cmd"
My project directory has the 3 files below.
rndbet/rndbet.py
while True:
s = input()
if s == "exit":
exit()
else:
print("I'm rndbet: " + s)
rndbet/start
python3 rndbet.py
mjhd.java
import java.io.PrintStream;
import java.util.Scanner;
public class mjhd {
public static void main(String[] args) throws Exception {
Process process = new ProcessBuilder("bash", "-c", "cd rndbet&&./start").start();
new Thread(new Runnable() {
#Override
public void run() {
Scanner in = new Scanner(process.getInputStream());
while (in.hasNextLine()) {
System.out.println("<- rndbet: " + in.nextLine());
}
}
}).start();
Scanner in = new Scanner(System.in);
PrintStream out = new PrintStream(process.getOutputStream(), true);
while (true) {
out.println(in.nextLine());
} //this part is actually broken; it shouldn't be an infinite loop
//just for testing
}
}
When I type bash -c "cd rndbet&&./start" directly from the command line, below happens.
$ bash -c "cd rndbet&&./start"
hi
I'm rndbet: hi
exit
But running the java program behaves differently.
$ java mjhd
hi
<- rndbet: I'm rndbet: hi
exit
<- rndbet: I'm rndbet: exit
exit
<- rndbet: I'm rndbet: exit
So now the Python script doesn't get the exit command correctly. Please help me fix this problem.
I've just found a problem that when the Python script is run via Java, an extra character of ASCII value 13 is always appended at the end of the sent text. What is a possible fix?
Okay I found a simple answer.
Changing out.println(in.nextLine()); to out.print(in.nextLine() + '\n') works.
I have a bash file:
REPOS="$1"
TXN="$2"
SVNLOOK=/usr/bin/svnlook
LOGMSG=$($SVNLOOK log -t "$TXN" "$REPOS" | grep "[a-zA-Z0-9]")
echo "\n$LOGMSG" >> /dev/tty
javac ~/Desktop/SomeClass.java
java ~/Desktop/SomeClass $LOGMSG
STATUS=$?
echo "\n" >> /dev/tty
echo $STATUS >> /dev/tty
exit 0
which calls this java file:
public class SomeClass {
public static void main(String[] args) {
String result = "";
for (String s: args) {
result = result + " " + s;
}
String regex = ".*\\bHello\\b.*";
if(result.matches(regex)) {
System.out.println("It matches");
System.exit(0);
} else {
System.out.println("It does not match");
System.exit(42);
}
}
}
I have never in the Java file have exited with the exit code of 1. However when I echo the status in the bash file, it always shows me '1' What can be the reason behind this?
The error code is because Java is failing to start. You aren't specifying the class to be run correctly.
If I have a class located in my desktop directory, I would need to use the following to run it from another directory:
java -cp ~/Desktop SomeClass
assuming that SomeClass has no package specified. If you have package org.foo.bar; at the top of the file, you would need to use
java -cp ~/Desktop org.foo.bar.SomeClass
I have created the shell script to add two numbers. I want to execute that shell script from java. Can you please help me on this.
first_num=0
second_num=0
echo -n "Enter the first number-->"
read first_num
echo -n "Enter the second number-->"
read second_num
echo "first number + second number = $ (( first_num + second_num ))"
And I need a piece of code based on the "jsch" library
you can do it by getting the runtime, as next
Process p = null;
Runtime rt = Runtime.getRuntime ();
String rutaFinal=path+carpeta+"/";
System.out.println("** Executing command *****");
p = rt.exec("chmod x process.sh");
p = rt.exec ("sh process.sh");
p.waitFor();
Also you can execute commands one by one, hope this help!!!