I am writing a java aplication that edits images using imagemagick commands;
However, the comands do not work and I am getting no output from them;
Actually, the comand identify is not recognized and I get CreateProcess error=2;
This seems odd, because the imagemagick instalation folder is included in my Path variable.
Here's my code:
public class Test {
public static void main(String argv[]) {
Runtime ru = Runtime.getRuntime();
Process p = null;
try {
//I've added this as a bouns, this should not be neccessary(methinks)
String[] s = {"C:\\Program Files\\ImageMagick-6.8.6-Q16"};
String[] cmd = {"convert", "acc-logo.jpg","-flip", "edited.jpg"};
p = ru.exec(cmd,s);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader ina = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = null;
try {
while ((line = ina.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have a space in the path to the executable, and the Runtime.exec() call is having problems with it. Use ProcessBuilder instead; it handles spaces in arguments much more easily.
Related
i am trying to develop pocketsphinx app. using terminal java gui-code in raspberry pi. The code is below. when started the application after 28 line its stops. Where is the problem? Thanks..
kamil
//-----------------------------------------------------------------------
//MIC TASK
//-----------------------------------------------------------------------
public class MIC_TASK implements Runnable {
public void run() {
Runtime rt = Runtime.getRuntime();
Process proc = null;
// sending pocketsphinx_continuous -inmic yes ... command
try {
proc = rt.exec("pocketsphinx_continuous -inmic yes -hmm /usr/local /share/pocketsphinx/model/hmm/en_US/hub4wsj_sc_8k "
+ "-lm /usr/local/share/pocketsphinx/model/lm/en/4135.lm -dict /usr/local/share/pocketsphinx/model/lm/en/4135.dic");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}///
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
while (true) {
try {
while ( (line = br.readLine()) != null) {
textArea_1.append(line+"\n\r");
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have this plugin that when installed, extracts some executables at some temporary location, and uses them. Here is my code:
public class StartCheck implements IStartup {
private BufferedReader buf=null;
public static String pathBandwidth;
public static String pathDeviceQuery;
public static String pathKernelLaunchOverhead;
public static String memoryLatency;
public void earlyStartup() {
// This method checks for presence of nvcc when Eclipse starts-up.
String command="nvcc --version";
Runtime run = Runtime.getRuntime();
Process pr;
try {
pr = run.exec(command);
pr.waitFor();
buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
//print-out the nvcc version
System.out.println(buf.readLine());
Preparation.return_val=true;
//extract the executables
Bundle bundle = Platform.getBundle("PTXAnalysis");
URL url_bandwidth = FileLocator.find(bundle, new Path("/Executables/bandWidth.out"), null);
URL url_deviceQuery = FileLocator.find(bundle, new Path("/Executables/deviceQuery.out"), null);
URL url_kernelLaunchOverhead = FileLocator.find(bundle, new Path("/Executables/empty"), null);
URL url_memoryLatency = FileLocator.find(bundle, new Path("/Executables/memLatency.out"), null);
try {
url_bandwidth = FileLocator.toFileURL(url_bandwidth);
url_deviceQuery = FileLocator.toFileURL(url_deviceQuery);
url_kernelLaunchOverhead = FileLocator.toFileURL(url_kernelLaunchOverhead);
url_memoryLatency = FileLocator.toFileURL(url_memoryLatency);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pathBandwidth=url_bandwidth.toString();
pathDeviceQuery=url_deviceQuery.toString();
pathKernelLaunchOverhead=url_kernelLaunchOverhead.toString();
memoryLatency=url_memoryLatency.toString();
}catch (IOException e) {
//disable all commands since no further task can be done, prompt user to install nvcc.
System.out.println("nvcc was not found on this computer. You won't be able to use the energy estimation plug-in");
EnergyEstimator.return_val=false;
Preparation.return_val=false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
When I install the plugin, it gives me this location (one of the many), where the executable has been extracted:
/home/limafoxtrottango/.eclipse/org.eclipse.platform_4.4.1_2069420271_linux_gtx_x86_64/configuration/org.eclipse.osgi/460/0/.cp/Executables/bandWidth.out
Now, the problems: I can't find any such directory. I understand that it is a temporary directory, but it does not show-up even if Eclipse is running. I am using one of these paths to run an executable using ProcessBuilder. Here is the code:
public static void runExecutable(){
initializeArray();
path_result="/home/"+System.getProperty("user.name")+"/kernelLaunchOverhead.txt";
String path_executable=StartCheck.pathKernelLaunchOverhead.substring(path_result.indexOf('/'),path_result.lastIndexOf('/')+1); //path to the directory in which the executable is extracted
try {
fw = new FileWriter(path_result);
for(int i=0;i<arr.length;i++){
ProcessBuilder builder=new ProcessBuilder("./empty",Integer.toString(arr[i]));
builder.directory(new File(path_executable));
int av=0;
float sum=0;
while(av<10){
Process pr=builder.start();
stdin = pr.getInputStream();
isr = new InputStreamReader(stdin);
br = new BufferedReader(isr);
sum=sum+Float.parseFloat(line=br.readLine());
av++;
}
fw.write(arr[i]+" "+Float.toString(sum/10));
fw.write("\n");
}
fw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FillArrays(path_result);
BestLineFit();
saveModel("/home/"+System.getProperty("user.name")+"/KernelLaunchOverheadModel.txt");
}
On invoking this function, nothing happens. It does not even throw any FileNotFound exceptions. Normally, it should have found the executable in the directory, and run it. But after installing the plugin, nothing happens.
To re-iterate, the class StartCheck is successfully showing to me the path to which the executables have been extracted. But those paths do not exist anywhere on my system.
Directories starting with . (such as the .eclipse in the path you show) are hidden on Linux and macOS systems.
You can see them from the command line using ls -a
Java is new to me.
I am executing a batch file using Runtime.getRuntime.exec(filename.bat) and this batch file executes a commandant encrypt.password -Dvalue=somevalue>log.txt and redirects its output to a log.txt file.
Problem that I am facing is batch file is working fine if I run it manually however when program executes it ,it just creates blank 'log.txt'
Content of mybat.bat batch file is as below:
cd/
c:
cd c:/ant_builds/thinclient
ant encrypt.password -Dvalue=someValue >C:/log.txt
Java code is as below:
Process p=Runtime.getRuntime.exec("C:\mybat.bat");
p.waitFor();
It seems that after creating the log file,meantime command is executing control comes out from process.
I have read almost 50 threads here however did not get the solution. Please help me out.
Use ProcessBuilder to create your process and call redirectOutput(File) to redirect and append output to a file.
Try this code:
public class Test {
ProcessBuilder builder;
Path log;
public Test() {
try
{
log = Paths.get("C:\\log.txt");
if (!Files.exists(log))
{
Files.createFile(log);
}
builder = new ProcessBuilder("ant", "encrypt.password", "-Dvalue=someValue");
builder.directory(Paths.get("C:\\ant_builds\\thinclient").toFile());
builder.redirectOutput(ProcessBuilder.Redirect.appendTo(log.toFile()));
builder.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test();
}
}
For jdk 1.6 or less, use the following code:
public class Test {
ProcessBuilder builder;
Path log;
Process process;
BufferedReader br;
PrintWriter pw;
Charset charset = Charset.forName("UTF-8");
public Test() {
try {
log = new File("C:\\log.txt");
if (!log.exists()) {
log.createNewFile();
}
builder = new ProcessBuilder("ant", "encrypt.password","-Dvalue=someValue");
builder.directory(new File("C:\\ant_builds\\thinclient"));
builder.redirectErrorStream(true);
process = builder.start();
br = new BufferedReader(new InputStreamReader(process.getInputStream(),charset));
pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(log, true), charset));
(new Thread() {
public void run() {
try {
while (process.isAlive()) {
String s = null;
while ((s = br.readLine()) != null) {
pw.print(s);
pw.flush();
}
}
br.close();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Test();
}
}
I'm not sure about the order and list of ProcessBuilder arguments so try to play with them to get your code working.
You can also read commands from a common file and redirect output and erros to a sepearate files. Redirect.appendTo is to avoid the process from overiting the existing logs.
Try this code:
try {
File commands = new File("D:/Sample/Commands.txt");
File output = new File("D:/Sample/Output.txt");
File errors = new File("D:/Sample/ErrorsLog.txt");
ProcessBuilder pb = new ProcessBuilder("cmd");
System.out.println(pb.redirectInput());
System.out.println(pb.redirectOutput());
System.out.println(pb.redirectError());
pb.redirectInput(commands);
pb.redirectError(Redirect.appendTo(errors));
pb.redirectOutput(Redirect.appendTo(output));
pb.redirectInput();
pb.redirectOutput();
pb.redirectError();
pb.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I've found this topic, but the code doesn't work for me... Return Windows cmd text from Java?
After pressing a button I want to execute a batch-file, for testing purposes it's just the ipconfig-command.
The cmd-output should be written into a JTextFiled, but all I get is no text...
Here the code for writing it into the JTextField:
btnLock.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String g = "";
try {
Runtime.getRuntime().exec(new String[] {"ipconfig", g});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Process p = null;
try {
p = Runtime.getRuntime().exec(new String[] {"ipconfig", g});
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream s = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(s));
String temp;
try {
while ((temp = in.readLine()) != null)
{
System.out.println(temp);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnLock.setBounds(10, 68, 89, 23);
contentPane.add(btnLock);
So what do I do wrong?
It's my first project with cmd-input, so please don't get mad cause of silly mistakes I made. ;)
Thx
Try the exec command that just takes a String parameter. The following test code worked on my system (though I was only printing to console, not to textfield):
BufferedReader in = null;
try{
Process p = Runtime.getRuntime().exec("ipconfig");
InputStream s = p.getInputStream();
in = new BufferedReader(new InputStreamReader(s));
String temp;
while ((temp = in.readLine()) != null) {
System.out.println(temp);
}
} catch (Exception e){
e.printStackTrace();
} finally {
if (in != null) in.close();
}
Also your code in the original post is also using a System.out.println. As far as I'm aware, you can't print to a JTextField using System.out.println.... You'd have to use the setText method.
If I run
ipconfig ""
I get
** Error: unrecognized or incomplete command line.**
You can only run from Java, commands which work on the command line.
BTW: If you are looking for errors, you need to read the error stream.
I would Runtime.getRuntime().exec(new String[] {"ipconfig > temp.txt"}); and then just read it as a text file using a BufferedReader.
I hope this helps.
How can I mount a .dmg file through java code under OS X?
This will work (but only on OS X):
try {
String[] command = {"/usr/bin/hdiutil", "attach", "/Users/path/to/your.dmg"};
String sendback = "";
Process proc = Runtime.getRuntime().exec(command);
InputStream istr = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
String str;
while ((str = br.readLine()) != null) {
sendback = sendback + str;
}
int resultCode = proc.waitFor();
br.close();
if (resultCode != 0) {
throw new Exception("failed to open system profiler");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DMGs are not executables, are apple diskimages
reference is here
thus you can't "run" it.
You can use a Process, of course. But it won't work anywhere except on a Mac.
Saying that is like asking how to run an ISO file through Java. You simply can't; it's a disk image.