I have a shell script that I want to execute in Eclipse from a Java code.
I am able to use external tools in order to run the script, but I want the script to run during the execution of the Java code i.e. the Java code should make a call to the script.
Earlier I was using the "Process Builder" to do so but it seems Eclipse does not support that method as it says "File not found" when I have given it all the permissions.
Any idea how to run the script from a Java code in Eclipse?
Here is the code:
String line1 = null;
String target = new String("/home/aditya_s/workspace/rs-test/src/iperf_parse.sh " + host + " " + "9000");
while(line1 == null)
{
Process p1 = Runtime.getRuntime().exec(target);
BufferedReader input1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
System.out.println("Ran");
line1 = input1.readLine();
p1.destroy();
}
BW = Double.parseDouble(line1);
TIP: Right click on the shell script and go to Properties. There give the 'Read/Write/Execute' permissions to 'Owner'. By default, the 'Execute' permission is not there. So you might get an error like 'Could not execute script.sh'.
Eclipse runs your java program just as it normally would, so ProcessBuilder will work as well. It is possible that you passed in the wrong path. If the path is relative, it will be relative to System.getProperty("user.dir").
You should be able to use the below, replace shellscript with the script you want to run.
String s = "shellscript";
Process proc = Runtime.getRuntime().exec(s);
You should look at ProcessBuilder
Related
if(os.contains("windows"))
{
File bat = new File(System.getenv("APPDATA") + "/SelfCommandPrompt", appId + "-run.bat");
bat.getParentFile().mkdirs();
List<String> list = new ArrayList(1);
list.add("#echo off");
list.add("start" + " \"" + appName + "\" " + command);
IOUtils.saveFileLines(list, bat, true);
ProcessBuilder pb = new ProcessBuilder(bat.getAbsolutePath());
//inherit IO and main directory
pb.directory(getProgramDir());
//fire the batch file
pb.start();
System.exit(0);
}
So I dynamically create a .bat file and I want to run the process but, NOT IN THE BACKGROUND. Java forces the process to happen in the background how do I make it so it's not in the background? I am not looking to get the output stream from the .bat file I only want to execute it with the native gui it's intended to use on double click. Everywhere I look on these forums it only tells me how to do it in the background and get the outputstream? Why isn't there a boolean for this in the process builder? For my program specifically right now I want to reboot my java program with command prompt terminal on double click. I have the command generation working I tested the .bat file but, java again forces it to happen in the background.
Another use for doing a process not in the background. A java launcher for a game which executes a program with the gui not in the background which I may also need in the future.
Also the bat files output which is dynamically generated based off of the enviorment
java -Dfile.encoding=Cp1252 -cp C:\Users\jredfox\Documents\MDK\md5-spreadsheet\filededuper\bin;C:\Users\jredfox\Documents\MDK\md5-spreadsheet\filededuper\libs\apache-codecs.jar jredfox.selfcmd.SelfCommandPrompt true jredfox.filededuper.Main
edit I figured out a command for windows but, only windows. I need commands for mac
Runtime.getRuntime().exec("cmd /c start" + " \"" + appName + "\" " + command);
Figured it out.
basically get the terminal string on linux you need to make an api for it
save any shell scripts you need in the appdata
make an api to get the app data folder
create your custom command
return if conditions are not met like the System.console != null for my thing yours will be different.
execute command in new terminal window therefore the new native terminal using os commands.
All the code is found here.
https://github.com/jredfox/OpenTerminal
I'm trying to run a java command in cmd using C# to get some inputs for my program, the path for Java is set correctly, and I am able to run Java commands in the cmd without any trouble but when I tried it in C#, it's showing " 'java' is not recognized as an internal or external command, operable program or batch file. " as if the path is not set.
But I am able to run the same command outside, don't know what seems to be the issue, kindly help, thanks in advance!
string cmd = #"/c java -jar """ + $"{treeEditDistanceDataFolder}libs" + $#"\RTED_v1.1.jar"" -f ""{f1}"" ""{f2}"" -c 1 1 1 -s heavy --switch -m";
Console.WriteLine(cmd);
var proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = cmd;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
Console.WriteLine("Process started");
string output = proc.StandardOutput.ReadToEnd();
Console.WriteLine("Output was read");
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();
This line is your problem:
proc.StartInfo.UseShellExecute = false;
When UseShellExecute is true, the system and user PATH variables will be used if the application to launch is just the executable name. Because you're setting it to false, and java doesn't exist in your application's folder, it isn't possible for .NET to find it.
You have two options:
Set UseShellExecute to true so that it can use the PATH variable to find java.
Use a fully qualified path, e.g. "C:\Program Files\Java\jdk1.8.0_101\bin\java"
See this answer for more info.
I'm trying to train a neural network to play Halite 3. The provided interface is a bash script which:
1. compiles my bot
2. calls the binary file with a string to run the bot java myBot
I'm trying to run this script from Java to train the network.
I've tried using a ProcessBuilder to run the script as well as the binary in the script. Running the script produces no output, and using echo I've determined that the program terminates when javac is called in the script. Removing that call, it terminates when the program is run.
I've tried calling the program directly as well using ProcessBuilder, and this does indeed produce output. The issue is it doesn't run the bots properly saying it can't find the file. I've tried changing the path to be relative to different directory levels as well as the absolute path (the java command doesn't seem to like absolute paths?).
Calling the binary directly:
List<String> cmd = new ArrayList<>();
cmd.add(dir+ "/src/halite");
// Replay
cmd.add("--replay-directory");
cmd.add(dir+"/replays/");
// Options
cmd.add("--results-as-json");
cmd.add("--no-logs");
// Dimensions
cmd.add("--width");
cmd.add("16");
cmd.add("--height");
cmd.add("16");
// Players
cmd.add("\"java -cp . myBot\"");
cmd.add("\"java -cp . myBot\"");
Process proc = new ProcessBuilder(cmd).start();
InputStream is = proc.getInputStream();
Scanner s = new Scanner(is);
while (s.hasNext()){
System.out.println((String) s.next());
}
This code does produce a JSON, however, I get an error in my logs saying that the bots do not run.
I am trying to start a new process with Runtime.exec() from my javafx application.
The new process is my javafx application (but in a new process, the "parent" one will still be open).
So I run javaw via the exec method and tell it my classpath. And here is my problem: the classpath contains whitespaces, so I need to quote every path. But I retrieve the path at runtime via java.class.path (since it is the same application).
Do I need to process the string and quote everything or is there an easy way to get this to work?
Here is the code:
public static void startInNewProcess() {
try {
Runtime r = Runtime.getRuntime();
File javaPath = new File(System.getProperty("java.home"), "bin/javaw");
File classPath = new File(System.getProperty("java.class.path"));
System.out.println("java loc: " + javaPath.toString());
System.out.println("classpath: " + classPath);
Process p = r.exec(javaPath.toString() + " -classpath " + classPath.getPath());
} catch (Exception e) {
e.printStackTrace();
}
}
I get the following string as classpath:
classpath: C:\Users\kwilhelm\git\ResourcePlaner\bin;C:\Program Files (x86)\eclipse\plugins\org.eclipse.fx.ide.css.jfx8_2.0.0.201506111511.jar;C:\Users\kwilhelm\git\ResourcePlaner\lib\itextpdf-5.5.6-javadoc.jar;C:\Users\kwilhelm\git\ResourcePlaner\lib\itextpdf-5.5.6-sources.jar;C:\Users\kwilhelm\git\ResourcePlaner\lib\itextpdf-5.5.6.jar;C:\Users\kwilhelm\git\ResourcePlaner\lib\controlsfx-8.40.9.jar
But javaw gives the error that it can't find mainclass "Files", so it can't handle the whitespace in the path.
So is there a way to get the classpath with quotes?
Is there a better solution?
Any help is apreciated
And here is my problem: the classpath contains whitespaces, so I need to quote every path.
Actually, no you don't.
And in fact, if you do attempt to quote every path, it is likely to mess up bigtime, because exec doesn't understand shell quoting.
What you actually need to do is this:
Process p = r.exec(new String[] {javaPath.toString(),
"-classpath",
classPath.getPath()});
This tells exec exactly where the boundaries of the command arguments are, so that it doesn't need to try (and fail) to figure it out for itself.
In fact, that still isn't right. You also need to add:
any other JVM options that the cloned instance needs,
a class name, and
any arguments required after the classname.
The classname is mandatory. (You left it out, and that is why the java command was outputting its help message!)
The following method starts the cmd in Windows and it takes a parameter of the command which need to be run.
I have tested this method using the following commands: net users and it worked fine and it printed the users accounts. but if I run the dir command I get the following error:
java.io.IOEXception:
Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified (in java.lang.ProcessBuilder)
Code :
private String commandOutPut;
public void startCommandLine(String s) throws IOException{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(s); // you might need the full path
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String commandOutPut;
while ((commandOutPut = br.readLine()) != null) {
this.commandOutPut = this.commandOutPut + "\n" + commandOutPut;
}
System.out.println(this.commandOutPut);
}
Well, obviously, your method does not start cmd. How did you get this notion?
The net command is a standalone command so it runs just fine, but the dir command is not standalone, it is an internal command of cmd.exe, so you cannot run it without launching cmd.exe to execute it.
To get it to work you will have to pass not dir but cmd.exe /c dir or something like that.
Don't know if this perception can help you. But, seems that "net users" are recognized as Windows command, since "Execute" dialog can run it.
But, for some reason, the "dir" command aren't. When try to run, Windows responds that command was not found.
Additionaly, I tried run Command with inline arguments too, but the arguments are simply ignored. (sorry for bad english)
My best guess is that this is because "net" is a real executable (there is a file WINDIR\System32\net.exe"), while "dir" is a builtin command of the command interpreter - it has no executable and is directly executed within cmd.exe.
Howevever you may get around this be invoking "dir" command inside the cmd process. The syntax - as per Microsoft docs - is:
cmd /c dir
There are also some related answers on the site:
How to execute cmd commands via Java
Run cmd commands through java
You can use the following code for this
import java.io.*;
public class demo
{
public static void main(String args[])
{
try
{
Process pro=Runtime.getRuntime().exec("cmd /c dir");
pro.waitFor();
BufferedReader redr=new BufferedReader(
new InputStreamReader(pro.getInputStream())
);
String ln;
while((ln = redr.readLine()) != null)
{
System.out.println(ln);
}
}
catch(Exception e) {}
System.out.println("Done");
}
}