Environment: Windows 10 (Java) -> Windows 10 (PowerShell and C#)
Java: 1.8.0_252
Trying to remotely execute a C# program via PowerShell from Java. Seem to be having issues with the path. The C# program is in a subdirectory under a shared drive.
import java.io.*;
public class CallCSharp {
public static void main(String[] args) {
try {
ProcessBuilder builder = new ProcessBuilder("powershell.exe", "/c",
"\\SharedDrive\\Data\\Bin\\Program.exe \\\\10.1.1.1 -u user -p password");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
} catch (Exception e){
e.printStackTrace();
}
}
}
The error returned is
The term '\SharedDrive\Data\Bin\Program.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
The path is correct and the C# program can be run successfully.
Suspect I am not formatting the ProcessBuilder call correctly.
Related
I'm on Windows 10, using ProcessBuilder to run a .exe from my Java program and using BufferedReader to get the number it outputs when it's provided the path that my Java program provides. It's working, but it's freezing the program for an unbearable while when it tries to get the output.
It worked smoothly when I tested it on Ubuntu 20, but I can't make it go fast on Windows. Also, if I run the .exe file from cmd, it goes fast as it should.
Here's my Main class code:
package teste;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
Process process;
String command = "src\\teste\\flir_image_extractor.exe -avg -i C:\\Users\\Daniel\\Desktop\\example.jpg";
try {
ProcessBuilder builder = new ProcessBuilder();
if (isWindows) {
builder.command("cmd.exe", "/c", command);
} else {
builder.command("sh", "-c", command);
}
System.out.println("this");
builder.directory(new File(System.getProperty("user.dir")));
builder.redirectErrorStream(true);
process = builder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line); // Do something with the return
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I tested it with prints, and it hangs just as it enters the while loop, so it looks like readLine() is the issue. Does anyone know what could be slowing it down?
I'm running the code in Eclipse.
I thank you in advance.
A few things to try. It may be the Eclipse console - some versions have been slow if there is a lot of output. You could test this by running this Java app from Windows command line to see if issue goes away, or you could remove your reader.readLine() / System.out.println loop and replace with transferTo:
try(var stdo = p.getInputStream()) {
stdo.transferTo(System.out);
}
Don't forget to wait for the process exit:
int rc = exec.waitFor();
If the Eclipse console is the issue, redirect output to a file before start and check the file afterwards:
pb.redirectOutput(new File("stdout.log"));
Ideally, don't use CMD.EXE / shell to run applications that may be run directly, try as:
String[]command = new String[] {"src\\teste\\flir_image_extractor.exe","-avg", "-i", "C:\\Users\\Daniel\\Desktop\\example.jpg"};
I am trying to print the output of a shell script on the console using java. When I manually run the script, I get
C:/Users/user1/Desktop/shell.sh: line 78: /usr/ucb/ps: No such file or directory
<STATUS>: Probe [ devicename ] is not running!
But, when I try to run it on my Java program, the output is not being printed on the console.
My code is:
ProcessBuilder processBuilder = new ProcessBuilder("C:/Program Files/Git/git-bash.exe","C:/Users/user1/Desktop/shell.sh");
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
System.out.println(line);
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
System.exit(0);
} else {
//abnormal...
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
The only output I am getting is "Success". When I debugged my code, I found that the code never enters the condition
while ((line = reader.readLine()) != null)
even though, in the bash terminal, there are lines of output. Why is this happening?
I am stuck at this point and I couldn't find any other explanations for this problem. Kindly help.
You are running git-bash.exe which opens as a windows application. Although Java has access to the stdout/stderr streams of git-bash.exe, these are not necessarily the same as the stdout/err of the internal launch of your shell script within git-bash.exe.
One way to see the stdout/err of your command would be to make a java friendly version of the .sh script which launches your original sh and redirects output to a specific files which you can then access within java afterwards.
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/Git/GIT-BASH.EXE","/c/Users/blah/somescript.sh");
somescript.sh:
#!/bin/sh
runtheoriginalcommand > ~/somepath.out 2> ~/somepath.err
You could also add extra args to wrapper to pass the out/err files to be used so there is no contention with any other launches or hardcoded output files.
My program is not running from eclipse but it is running through terminal in ubuntu.
Below is the shell script that i am running in java
#!/usr/bin/env bash
# Running sqoop commands
s="$(sqoop help)"
echo "$s"
Below is the java code
package flexibility;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Flex {
public static void main(String args[]) throws Exception {
String s = null;
String line = "";
String sqoopCommand = "sqoop help";
try {
Process p = Runtime.getRuntime().exec("/home/avinash/sqoop.sh");
p.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = stdInput.readLine()) != null) {
output.append(line + "\n");
}
while ((line = stdError.readLine()) != null) {
output.append(line + "\n");
}
System.out.println("### " + output);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
error message :
/home/avinash/sqoop.sh: line 5: sqoop: command not found
Try with the command "sh /home/avinash/sqoop.sh". I feel since the ubuntu isn't aware what kind of file it is,It's clearly throwing command not found error.
The error message is from your script. Not from Eclipse.
Eclipse (or the JVM to be more precise) does not know about the environment variables or working directory of the script. In contrast: If you run the script from command line environment variables (e.g. PATH) or working directory are known.
You can use method Runtime.exec(String command, String[] envp, File dir) to specify this in your Java code. So I guess this should work:
Process p =
Runtime.getRuntime().exec("/home/avinash/sqoop.sh", null, new File("/home/avinash/"));
I am developing a Java application which will execute a console command. What the command actually does is, it will make changes to a file, then will save a copy of it with a different name to a different folder (both of the file and the output folder is specified by the user). And it requires some binary program to do this, which is a local resource of my application.
So my code is something like:
...
public void actionPerformed(ActionEvent e) {
File selectedFile = jFileChooser1.getSelectedFile();
File pathAssigned = jFileChooser2.getSelectedFile();
String file = selectedFile.getAbsolutePath();
String output = pathAssigned.getAbsolutePath();
String name = selectedFile.getName();
// What's next???
}
And the usage/syntax of the command is something like:
"command -options /package/binary.bin "+file+" "+output+"\\"+name+"-changed"
So my question would now be; What will be my next code? Should I use a Runtime? If so, then how?
And about including a local resource path to a command, does my syntax is correct?
I am still a newbie here as well as in Java programming so please be kind to your answers/comments. Thanks!
PS. The command is a platform independent by the way.
I hope the code below can help you. First you have a shell script that takes parameters.
#!/bin/bash
echo "hola"
echo "First arg: $1"
echo "Second arg: $2"
You save it in e.g. /home/dac/proj/javatest2016/src/main/java/myshellScript.sh and then you can pass the parameters from your Java code.
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
try {
ProcessBuilder pb = new ProcessBuilder("/home/dac/proj/javatest2016/src/main/java/myshellScript.sh", "myArg1", "myArg2");
pb.directory(new File("/home/dac/proj/javatest2016/src/main/java"));
Process p = pb.start();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
System.out.println("### " + output);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Test
### hola
First arg: myArg1
Second arg: myArg2
I am playing around with some GIT commands in terminal, but I want to write a java program to automate the process.Please note I am not writing a program straight into a terminal. I am writing it in eclipse. This following code works on windows, but not MAC. How should I change it to run on MAC?
import java.io.*;
public class NewClass {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("GIT");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
"GIT" should be "git" for case sensitive systems like Mac OS. Note that without arguments, this will only give you a listing of the git syntax.
Please follow the basic steps outlined in this CS article from Princeton (How to run Java Program on a Mac)