Reputation: 1601
I'm trying to run process builder to execute a file which is inside my bin/resources/ folder of my java project. For that, I don't want to hard code the complete path, so I'm trying to pass absolute path (full path I mean) using class loader and pass this value as a list argument to ProcessBuilder class. How ever I'm not able to succeed in doing so.
Below code samples (both Case 1 and 2) run fine but nothing happening in the end. I mean the file is not getting called.
Case 1:
String rCmd = "Rscript.exe";
String rScriptName = "resources/MyScript.R";
List list = new ArrayList<>();
list.add(rCmd);
list.add(this.getClass().getClassLoader().getResource(rScriptName).toURI().toString());
ProcessBuilder pb = new ProcessBuilder(list);
pb.start();
Case 2:
String rCmd = "Rscript.exe";
String rScriptName = "resources/MyScript.R";
List list = new ArrayList<>();
list.add(rCmd);
list.add(this.getClass().getClassLoader().getResource(rScriptName).toString());
ProcessBuilder pb = new ProcessBuilder(list);
pb.start();
Below piece of code throwing exception:
Case 3:
String rCmd = "Rscript.exe";
String rScriptName = "resources/MyScript.R";
List list = new ArrayList<>();
list.add(rCmd);
list.add(this.getClass().getClassLoader().getResource(rScriptName).toURI());
ProcessBuilder pb = new ProcessBuilder(list);
pb.start();
Case 4:
File file = new File(this.getClass().getClassLoader().getResource(rScriptName).toURI());
List list = new ArrayList<>();
list.add(rCmd);
list.add(file);
ProcessBuilder pb = new ProcessBuilder(list);
pb.start();
Output:
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.ArrayList.toArray(ArrayList.java:361)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1005)
Below code gives me expected output but don't want to hard code the path this way, as I need to run this code in linux box later.
String rCmd = "Rscript.exe";
String rScriptName = "D:/MyScript.R";
ProcessBuilder pb = new ProcessBuilder(rCmd, rScriptName);
pb.start();
Expecting your much needed help on this!
Upvotes: 0
Views: 1984
Reputation: 822
String rCmd = "Rscript.exe";
String rScriptName = "filename Without Resource";
List list = new ArrayList<>();
list.add(rCmd);
list.add([Class name].class.getClassLoader().getResource(rScriptName).toURI().getPath());
Was working.
Process builder Expect String Argument So try to parse the list and it will give the below exception unless they are strings.
Try this.class.getClassLoader().getResource(rScriptName).toURI().getPath()
It will add the absolute path of the file and it will execute.
Upvotes: 1