Running exe using java

Running exe file with arguments from java program and sending output to text file

I want to run a exe file that accepts a mp3 file as an argument and redirects the output to a text file. I am using the below command from command prompt and its running fine and making a log.txt file in my binary folder however I am unable to do so by java.

 C:\Users\Desktop\binary>codegen.exe kalimba.mp3 > log.txt 
 File f = new File("C:/Users/Desktop/binary"); ProcessBuilder pb = new ProcessBuilder("cmd", "/c","start","codegen.exe", "kalimba.mp3", "log.txt"); pb.directory(f); 

3 Answers 3

You should use ProcessBuilder itself to redirect the output to a file. Specifically, the redirectOutput(File) method:

final File outFile = new File(. ); pb.redirectOutput(outFile); 

The redirection using > (in cmd as well as with Unix shells) is handled by the command interpreter/shell.

Actually I have to run it in JDK version 6 and that doesnt have the redirectOutputMethod as its newly added.

I would suggest using Apache’s Commons Exec as an alternative. It’s very intuitive and easy to work with, plus it’s friendly with different platforms.

Take a look a the Tutorial and see if it suits your needs. If so, take a look at this Question about how to capture the output stream of the resulting Process from the command.

If using ProcessBuilder is a requirement, take a look at the example on ProcessBuilder ‘s Documentation Page. It shows exactly what you want.

Читайте также:  imgExample

I finally managed to get it done 🙂

 ProcessBuilder pb = new ProcessBuilder("C:/Users/Desktop/binary/codegen.exe", "C:/Users/Desktop/binary/Kalimba.mp3"); Process process = pb.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(process .getInputStream())); FileHandler fh = new FileHandler("D:/log.txt"); Logger logger = Logger.getLogger("global"); logger.addHandler(fh); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); String line = null; while ((line = stdInput.readLine()) != null) < logger.log(Level.INFO, line); >System.out.println("Logging Completed. "); 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to run exe file in Java program

This code runs the file. This file have some section that I can click it and run different part of it. Is it possible that I can use a code to access to that sections and run them in Java instead of clicking it? edited code :

 Process process = Runtime.getRuntime().exec( "cmd.exe /C start C:/Users/123/Desktop/nlp.exe" ); Robot bot = new Robot(); bot.mouseMove(100, 100); bot.mousePress(InputEvent.BUTTON1_MASK); bot.mouseRelease(InputEvent.BUTTON1_MASK); 

I don’t quite get your question but if nlp.exe is the application where you have to do a click selection then please check whether the application supports command line parameters.

3 Answers 3

You can send a click signal to the system and specify its position on the screen. Check this question

You have to compute it on your own. I don’t think you can get any information about the content of the GUI.

it takes time to program run, so first robot click and then program run. what should I do to first run program and after that robot click?

Use java.awt.Robot to generate a system mouse click for an external program.

There is no built-in way with Java to get an external window’s coordinates, but it can be done using JNA. See this answer:

Your comments and editing are changing the question, which is making answering here almost pointless. Per your last edit to the question though, if I understand correctly, you are now asking if possible to somehow trigger an event in the external application with Java, without triggering the mouse click. In this case I think the answer is highly specific to the individual program.

If the event can be triggered via keypresses, then that might an another non-mouse option using java.awt.Robot .

If the program generates/responds to a Windows Message (at the windows api level), you could possibly send the same message via JNA and the windows api SendMessage . However, that can get complicated and requires that you are familiar with windows API and techniques for finding and working with those messages.

Источник

How to open an exe file in java

I am trying to use java to open an exe file. I’m not sure which program I want to open so I am using Skype as an example. When I try to do it, it gives me errors.

error: Cannot run program «C:\Program»: CreateProcess error=2, The system cannot find the file specified

4 Answers 4

String path = "/path/to/my_app.exe"; File file = new File(path); if (! file.exists()) < throw new IllegalArgumentException("The file " + path + " does not exist"); >Process p = Runtime.getRuntime().exec(file.getAbsolutePath()); 

You have to use a string array, change to

try < Process p = Runtime.getRuntime().exec(new String[] ); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >

If the String[] method works, and the String method doesn’t, that implies some sort of difference in implementation with how the executable is loaded between the two methods, which is just awful. I wonder if the OpenJDK environment (or any other Java implementations) has this same behavior, or if the spec says something about differences in behavior with these two methods.

You are on windows so you have to include the extension .exe

Maybe use File.separator instead of ‘\’

I tried this and it works fine, it’s taken from your example. Pay attention to the double \\

public static void main(String[] args) < try < Process p; p = Runtime.getRuntime().exec("C:\\Program Files\\Java\\jdk1.8.0_05\\bin\\Jconsole.exe"); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> 

Источник

Run exe which is packaged inside jar file

I am executing an exe through my java program. The path is hardcoded in Java. I have packaged my the exe in the jar. But am stuck as I have the path name hardcoded in the Java file, so I am not able to execute my jar as a stand alone program. Any hints for packaging such jar i.e having an exe inside and able to run it as a stand alone program?

6 Answers 6

This will extract the .exe to a local file on the local disk. The file will be deleted when the Java program exists.

import java.io.Closeable; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; public class Main < public static void main(final String[] args) throws URISyntaxException, ZipException, IOException < final URI uri; final URI exe; uri = getJarURI(); exe = getFile(uri, "Main.class"); System.out.println(exe); >private static URI getJarURI() throws URISyntaxException < final ProtectionDomain domain; final CodeSource source; final URL url; final URI uri; domain = Main.class.getProtectionDomain(); source = domain.getCodeSource(); url = source.getLocation(); uri = url.toURI(); return (uri); >private static URI getFile(final URI where, final String fileName) throws ZipException, IOException < final File location; final URI fileURI; location = new File(where); // not in a JAR, just return the path on disk if(location.isDirectory()) < fileURI = URI.create(where.toString() + fileName); >else < final ZipFile zipFile; zipFile = new ZipFile(location); try < fileURI = extract(zipFile, fileName); >finally < zipFile.close(); >> return (fileURI); > private static URI extract(final ZipFile zipFile, final String fileName) throws IOException < final File tempFile; final ZipEntry entry; final InputStream zipStream; OutputStream fileStream; tempFile = File.createTempFile(fileName, Long.toString(System.currentTimeMillis())); tempFile.deleteOnExit(); entry = zipFile.getEntry(fileName); if(entry == null) < throw new FileNotFoundException("cannot find file: " + fileName + " in archive: " + zipFile.getName()); >zipStream = zipFile.getInputStream(entry); fileStream = null; try < final byte[] buf; int i; fileStream = new FileOutputStream(tempFile); buf = new byte[1024]; i = 0; while((i = zipStream.read(buf)) != -1) < fileStream.write(buf, 0, i); >> finally < close(zipStream); close(fileStream); >return (tempFile.toURI()); > private static void close(final Closeable stream) < if(stream != null) < try < stream.close(); >catch(final IOException ex) < ex.printStackTrace(); >> > > 

Источник

Running exe from java code

I’ve been working on in a swing application. I’ve a JFrame having some buttons and fields. On some button click event,I’m opening an exe from my current directory. Everything works fine.

try < Runtime.getRuntime().exec(System.getProperty("user.dir") + "\\Upgrade\\Upgrade.exe"); >catch (IOException ex) < ex.printStacktrace(); >this.dispose(); // disposing my current java file. 

But what i need is to exit the java code after opening the exe file. Anyone help to deal this.?

2 Answers 2

Can you try making it a process, then waiting for that process to finish before exiting, like so:

class SO < public static void main(String args[]) < try < Process proc = Runtime.getRuntime().exec("your command"); proc.waitFor(); //Wait for it to finish System.exit(0); >catch (IOException e) < e.printStackTrace(); >catch (InterruptedException e) < e.printStackTrace(); >> > 

@SanCJ Glad it works, when you can the chance may I please have a green tick to show the questions as having an accepted answer =D

Executing an application from java using Runtime.exec() is a source of well known problems. Like waiting for a Process to finish, but not consuming the data from the stream buffers is a sure way for you application to hang.

I would suggest you use a library like Apache Common Exec to handle this.

I worked on a project a while back where we used Runtime.exec() to launch a process that would eventually extract files over existing files. All worked well except on one machine used for staging — it would just hang. It turned out on that staging machine, someone had set the date/time back so it looked liked the new files being extracted where older than the existing one, causing the external process to generate a warning message for each, overflowing the error buffer — which our application was not consuming!

Источник

Оцените статью