0

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

I have tried the ProcessBuilder class however cannot see the log.txt made in the binary folder

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

Any idea what I might be doing wrong?

Wanderer
  • 366
  • 2
  • 6
  • 18

3 Answers3

2

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.

fge
  • 119,121
  • 33
  • 254
  • 329
0

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.

Community
  • 1
  • 1
Alexis Leclerc
  • 1,303
  • 1
  • 16
  • 26
0

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...");
Wanderer
  • 366
  • 2
  • 6
  • 18