sorry when I tag ffmpeg because I couldn't tag MP4Box.But I have proplem with excuted with ffmpeg via javacode too.
I read at How to execute cmd commands via Java but i can't find my proplem.
I'm tested commands in cmd, it was ok:
MP4Box -dash 10000 -dash-profile live -segment-name output- seg -rap
-bs-switching no input.mp4
but when i executed cmd via java code , i get error:
Error - only one input file found as argument, please check usage
Below is my code, has something wrong?
package com.uit.reformatvideo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Logger;
public class ExecuteComandToFormatVideo {
public final static String LINK_MP4BOX = "C:/MP4Box/Tools/MP4Box.exe";
public final static String CREATE_MPD_ECLIPSE = "mp4box -dash 10000 -frag 1000 -rap -bs-switching no";
public final static String CREATE_MPD_IE = "MP4Box -dash 10000 -dash-profile live -segment-name output-seg -rap -bs-switching no";
private static final Logger log = Logger.getLogger(ExecuteComandToFormatVideo.class.getName());
public static void main(String[] args) throws IOException, InterruptedException {
String s = null;
try {
// run the Unix "ps -ef" command
// using the Runtime exec method:
String lsCmd[] = new String [2];
lsCmd[0] = LINK_MP4BOX;
lsCmd[1] = "MP4Box -dash 10000 -dash-profile live -segment-name output-seg -rap -bs-switching no input.mp4";
Process p = Runtime.getRuntime().exec(lsCmd);
p.waitFor();
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
System.exit(0);
}
catch (IOException e) {
System.out.println("exception happened - here's what I know: ");
e.printStackTrace();
System.exit(-1);
}
}
}
Here was out put:
Here is the standard output of the command:
Here is the standarderror of the command (if any): Error - only one
input file found as argument, please check usage
sorry because my English is bad. I created a bat file which included command such as CMD, then I used Runtime.getRuntime().exec(url+name+".bat");
to execute the bat file. This is my solution.
My bat file:
cd C:/MP4Box/Tools/
MP4Box
MP4Box -dash 10000 -dash-profile live -segment-name output-seg -rap -bs-switching no "C:\Users\ducth\Desktop\New folder (2)\SharingVideo\src\main\webapp\resources\video\output.mp4"
Related
I have a java program it does execute the shell command then wait for command to exit from shell to get result. But Process unable to read the output from command it just print result empty.
However same command if I run from shell prompt I could see result printing there..
{
[root#localhost home]# tsp -I marker input.mpg -P marker -a 10 -v 10 -O file output.mpg
marker: 10
marker: 20
marker: 30
marker: 40
marker: 50
marker: 60
marker: 70
marker: 80
marker: 90
marker: 100
marker: OK
[root#localhost home]#
}
Java program to execute shell command here
{
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteShellComand {
public static void main(String[] args) {
ExecuteShellComand obj = new ExecuteShellComand();
String command = "tsp -I olesmarker input.mpg -P " + "olesmarker -a 10 -v 10 -O file output.mpg";
String output = obj.executeCommand(command);
System.out.println("Command Result = " + output);
}
private String executeCommand(String command) {
StringBuilder output = new StringBuilder();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
Are you sure that your "tsp" program is generating these "marker" progress messages to standard out? Some programs are using the shell standard err channel. Especially programs doing conversions (the '-O file output.mpg' kind of indicates such a functionality) often use the shell-std.out as default output for conversion result and the shell-sdt.err for status and progress messages. (very useful for connecting commands with pipes on the shell).
I would suggest to try
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
instead of
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
Hope this helps..
How do I execute shell script file with an input parameter like "./flows.sh suspend" and print the the result to a file using java in linux?
This is a simple code to execute the shell script and read its output:
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
String[] command = { "./flows.sh", "suspend" };
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String s;
while ((s = reader.readLine()) != null) {
System.out.println("Script output: " + s); // Replace this line with the code to print the result to file
}
}
}
To print it to a file, just replace the System.out.println for the code to write into a file
You can use the JSCH API:
http://www.jcraft.com/jsch/examples/Shell.java.html
http://www.jcraft.com/jsch/examples/Exec.java.html
Bye!
I am trying to run wc -l filename command using Runtime.getRuntime().exec(command) and get the total number of lines. But it is not working.
Here is my code :
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
System.out.println(command);
p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line.split("\\s+")[0] + "\n");
}
int exc = p.waitFor();
System.out.println(exc);
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
exc (the exit value) is coming out zero. When I am printing the command which I am passing, it gives the right command. I have also tried to copy that command and run it in Linux. It's working, but not through program.
Command which I am passing to command variable in the functionexecuteCommand is:
wc -l < log1
Total number of lines it contains around 4597110. Also I dont want the size of file in bytes, I have to get the total number of lines only.
An easier alternative for getting the lines (with Java 8).
long lines = Files.lines(Paths.get("foo.txt")).count();
Kayaman has a much better answer if you're on Java 8 or better. If, however, you're stuck on an earlier iteration, see below.
You see this bit of code that you use for evaluating the output of wc:
while ((line = reader.readLine())!= null) {
output.append(line.split("\\s+")[0] + "\n");
}
That's remarkably similar to the code that could just read the file directly and count the number of lines.
So I'm not entirely certain why you think there's a need to call an external program to do this task, especially as it degrades the portabilty of your code.
Just open the file and read the lines, adding one to a counter for each line. And there you have it, the line count.
See, for example, the following file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class Test
{
static private int getLineCount(String fspec) {
String line;
int count = 0;
try {
BufferedReader reader = new BufferedReader(
new FileReader(new File(fspec)));
while ((line = reader.readLine())!= null)
count++;
} catch (Exception e) {
count = -1;
}
return count;
}
public static void main(String[] args) {
System.out.println (getLineCount("/tmp/tempfile"));
}
}
Running this gives 140 as does the output from wc -l:
pax> wc -l /tmp/tempfile
140 /tmp/tempfile
Looks like you don't pass correct path to the file, try this when you run method:
URL fileName = ClassLoader.getSystemClassLoader().getResource("filename");
System.out.println(executeCommand("wc -l " + fileName.getPath()));
Try using Process in the following way:
ProcessBuilder pb = new ProcessBuilder("wc", "-l");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));){
Process process = pb.start();
while (reader.readLine() != null){
// you need to figure out in which line the
// relevant output is and parse that to int
// just look at some sample outputs of wc -l
}
int err = process.waitFor();
if(err!=0) {
// your code for processing the number of lines goes here
// the command finished without error
}
else {
// your code here in case the command had an error
}
} catch (Exception e){
// catch an Exception like IOException or InterruptedException here
}
Basically the Reader will read the output from the command that would go to the terminal when executing the command there.
You can use apache common io FileUtils.readLines(File file)
FileUtils.readLines(new File("filename.txt")).size()
Good day, I thank who can help me in advance.
I need to run a command to read a file that contains the input data of a program and it will return a file with the output data.
Criteria:
I must locate myself in the folder where is the executable file of the software, then I write the following command:
swmm5 prueba1.inp prueba1.rpt prueba1.out
If I run it in the cmd, it generates output files:
swmm5 is the executable file
test1.inp is the file with the input data
test1.rpt is an output data file (this file is created when I run the command)
test1.out is the file with the output data (this file is created when I run the command)
The code I'm trying to use is this, although it generate no errors, it does not run the above command line successfully, because it does not generate the output files. Also I tried with the String that is in comments // (comando)
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class OptimizarSWMM {
public static void main(String[] args) {
Runtime cmd = Runtime.getRuntime();
Process proceso;
String[] directorio = new String[4];
directorio[0] = "cmd.exe";
directorio[1] = "/C";
directorio[2] = "C:\\Users\\milton\\Desktop\\EPA_SWMM_5.1";
directorio[3] = "swmm5 prueba1.inp prueba1.rpt prueba1.out";
//String comando = "cmd /C C:\\Users\\milton\\Desktop\\EPA_SWMM_5.1 swmm5 prueba1.inp prueba1.rpt prueba1.out";
try {
proceso = cmd.exec(directorio);
//proceso = cmd.exec(comando);
} catch (IOException ex) {
Logger.getLogger(OptimizarSWMM.class.getName()).log(Level.SEVERE,null, ex);
}
}
}
i could solve it thus:
"cmd.exe", "/c", "cd \"C:\\Users\\milton\\Desktop\\EPA_SWMM_5.1\" && swmm5 prueba1.inp prueba1.rpt prueba1.out"
this is the code:
public static void main(String[] args) throws IOException {
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", "cd \"C:\\Users\\milton\\Desktop\\EPA_SWMM_5.1\" && swmm5 prueba1.inp prueba1.rpt prueba1.out");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
I am trying to execute some Linux commands from Java using redirection (>&) and pipes (|). How can Java invoke csh or bash commands?
I tried to use this:
Process p = Runtime.getRuntime().exec("shell command");
But it's not compatible with redirections or pipes.
exec does not execute a command in your shell
try
Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});
instead.
EDIT::
I don't have csh on my system so I used bash instead. The following worked for me
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(final String[] args) throws IOException, InterruptedException {
//Build command
List<String> commands = new ArrayList<String>();
commands.add("/bin/cat");
//Add arguments
commands.add("/home/narek/pk.txt");
System.out.println(commands);
//Run macro on target
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("/home/narek"));
pb.redirectErrorStream(true);
Process process = pb.start();
//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while ((line = br.readLine()) != null)
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
System.out.println(line);
}
//Check result
if (process.waitFor() == 0) {
System.out.println("Success!");
System.exit(0);
}
//Abnormal termination: Log command parameters and output and throw ExecutionException
System.err.println(commands);
System.err.println(out.toString());
System.exit(1);
}
}
Building on #Tim's example to make a self-contained method:
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Shell {
/** Returns null if it failed for some reason.
*/
public static ArrayList<String> command(final String cmdline,
final String directory) {
try {
Process process =
new ProcessBuilder(new String[] {"bash", "-c", cmdline})
.redirectErrorStream(true)
.directory(new File(directory))
.start();
ArrayList<String> output = new ArrayList<String>();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while ( (line = br.readLine()) != null )
output.add(line);
//There should really be a timeout here.
if (0 != process.waitFor())
return null;
return output;
} catch (Exception e) {
//Warning: doing this is no good in high quality applications.
//Instead, present appropriate error messages to the user.
//But it's perfectly fine for prototyping.
return null;
}
}
public static void main(String[] args) {
test("which bash");
test("find . -type f -printf '%T#\\\\t%p\\\\n' "
+ "| sort -n | cut -f 2- | "
+ "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt");
}
static void test(String cmdline) {
ArrayList<String> output = command(cmdline, ".");
if (null == output)
System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
else
for (String line : output)
System.out.println(line);
}
}
(The test example is a command that lists all files in a directory and its subdirectories, recursively, in chronological order.)
By the way, if somebody can tell me why I need four and eight backslashes there, instead of two and four, I can learn something. There is one more level of unescaping happening than what I am counting.
Edit: Just tried this same code on Linux, and there it turns out that I need half as many backslashes in the test command! (That is: the expected number of two and four.) Now it's no longer just weird, it's a portability problem.