i try to convert video using ffmpeg in ubuntu.
ffmpeg -i inputfile.flv -sameq outputfile.mpeg
this works if change directory to inputfile directory.
is that posible to use this command ?
ffmpeg -i "home/Documents/inputfile.flv" -sameq "home/Documents/outputfile.mpeg"
i don't want to change directory when i use that command, because that command is using for my java code.
so my input file and output file is variable in my code .
here's my full code
package Converter;
import Controller.ConvertedButtonListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
/**
*
* #author roylisto
*/
public class VideoConverter {
private String defaultFile;
private String convertedFile;
private ConverterThread myThread;
private ConvertedButtonListener butListener;
public VideoConverter(String fileDir,String convertOutput,ConvertedButtonListener buttonListener){
this.defaultFile=fileDir;
this.convertedFile=convertOutput;
this.butListener=buttonListener;
}
public void convertToMjpeg(){
String[] listCommands={"ffmpeg","-i","\""+defaultFile+"\"","-qscale","0","\""+convertedFile+"\""};
myThread=new ConverterThread(listCommands,this);
myThread.start();
}
public void setCommandStream(String stream){
butListener.setCommandOutput(stream);
}
class ConverterThread extends Thread{
VideoConverter vc;
String[] command;
ConverterThread(String[] command,VideoConverter vc){
this.command=command;
this.vc=vc;
}
public void run(){
synchronized(vc){
try{
String s = null;
Process process = new ProcessBuilder(command).start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
StringBuffer start= new StringBuffer();
// read the output from the command
while ((s = stdInput.readLine()) != null)
{
start.append(s);
vc.setCommandStream(s);
}
stdInput.close();
// read any errors from the attempted command
while ((s = stdError.readLine()) != null)
{
start.append(s);
vc.setCommandStream(s);
}
}catch(Exception ex){
System.out.println(ex.toString());
}
}
}
}
}
until now my code works well in windows with some modification like change ffmpeg to ffmpeg.exe because ffmpeg isn't native in my windows. but when i use my code in ubuntu
it show this error
"/home/roylisto/Documents/Tugas Akhir/Video Master/3a.avi": No such file or directory
UPDATE
solve problem, here's my code :)
package Converter;
import Controller.ConvertedButtonListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
/**
*
* #author roylisto
*/
public class VideoConverter {
private String defaultFile;
private String convertedFile;
private ConverterThread myThread;
private ConvertedButtonListener butListener;
public VideoConverter(String fileDir,String convertOutput,ConvertedButtonListener buttonListener){
this.defaultFile=fileDir;
this.convertedFile=convertOutput;
this.butListener=buttonListener;
}
public void convertToMjpeg(){
String[] listCommands={"ffmpeg","-i",defaultFile,"-qscale","0",convertedFile};
myThread=new ConverterThread(listCommands,this);
myThread.start();
}
public void setCommandStream(String stream){
butListener.setCommandOutput(stream);
}
class ConverterThread extends Thread{
VideoConverter vc;
String[] command;
ConverterThread(String[] command,VideoConverter vc){
this.command=command;
this.vc=vc;
}
public void run(){
synchronized(vc){
try{
String s = null;
Process process = new ProcessBuilder(command).start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
StringBuffer start= new StringBuffer();
// read the output from the command
while ((s = stdInput.readLine()) != null)
{
start.append(s);
vc.setCommandStream(s);
}
stdInput.close();
// read any errors from the attempted command
while ((s = stdError.readLine()) != null)
{
start.append(s);
vc.setCommandStream(s);
}
}catch(Exception ex){
System.out.println(ex.toString());
}
}
}
}
}
is that posible to use this command ?
Yes, it is possible, as long as you specify a valid absolute or a relative path:
"home/Documents/inputfile.flv"
Should be:
"/home/Documents/inputfile.flv"
Otherwise it'd look for a home directory inside the current working directory. Notice the / at the beginning.
And as for this:
"/home/roylisto/Documents/Tugas Akhir/Video Master/3a.avi": No such file or directory
Are you really shure the file is there and you have r/w access to that directory?
Related
In my idea IDE, I can see the compile error with red font in the console.But when I deploy the jar in the linux server.I can not see the compile log.How to print the compile error log?
public static void main(String[] args) throws Exception {
String compliePath="D:\\testFole";
String filename="D:\\test.java";
String[] arg = new String[] { "-d", compliePath, filename };
System.out.println(com.sun.tools.javac.Main.compile(arg));
}
Well if I got your question right, here is an approach to the outcome.
I think this will be platform-independent.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
private static Process process;
public static void main(String[] args) {
runCommand();
getErrorMessage();
}
/**
* This method executes/runs the commands
*/
private static void runCommand()
{
File file = new File("D:\\\\test.java");
String changeDirectory = "cmd start cmd.exe /c cd D:\\";
String compile = " && javac D:\\test.java";
String run = " && java "+file.getName().replace(".java","");
String command = changeDirectory + compile + run;
try {
process = Runtime.getRuntime().exec(command);
}catch (IOException e){}
}
/**
* This method will get the errorStream from process
* and output it on the console.
*/
private static void getErrorMessage()
{
try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())))
{
String line;
if(errorReader.readLine() != null)
while ((line = errorReader.readLine()) != null)
System.out.println(line); //display error message
}catch (IOException e){}
}
}
I am working on a command line java program in eclipse. I used System.out.println to write to the console. It worked when I ran it with eclipse, but when I compiled it to a jar file, and ran it through cmd, it didn't write anything to the screen. Everything I looked up said to use System.out.println to write to command line. What should I do? Here is my code:
package cpac;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class packfile {
static double vernum = 1.1;
public static void saveUrl(final String in2, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(in2);
final byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
}
public static void main (String[] args) throws IOException {
int where = 0;
System.out.println("CPac Version " + vernum);
for (String s: args) {
if (s.equals("update")) {
java.io.File file = new java.io.File("cpac.jar");
file.delete();
saveUrl("cpac.jar", "http://example.com/package/cpac.jar");
return;
}
if (s.equals("install")) {
System.out.println("install");
URL oracle = new URL("http://example.com/package/" + args[where + 1] +"/package.pac");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
String data = null;
while ((inputLine = in.readLine()) != null){
data = inputLine;
}
in.close();
saveUrl(data, "http://example.com/package/" + args[where + 1] +"/" + data);
System.out.println("Done!");
}
where = where + 1;
}
}
}
EDIT:
I just read something that says you can't run jar files by typing their name in cmd. Is there any way to not have to type a long command without needing an extra file?
It would help to see what you entered on the command line. Hopefully it looks something like this.
java -cp <filename.jar> cpac.packfile
"Worked in Eclipse" - an IDE is keeping you from understanding how things really work.
You don't run JAR files; you run the JRE and tell it to use a JAR file to find the main class that you specify in the META-INF/manifest.mf.
Are there no messages in the console? Do you get no feedback? If you create the executable JAR properly, your main class will run. If your main class runs, it will write to the command shell when you print to the console.
I have to run a run a python script from a maven project. I created a temporary class with main method to check if it works as expected, used the process builder and it works if I specify the absolute path of the python script and then run the java class from eclipse using RUN as Java application.
If I change it getClass().getResourceAsStream("/scripts/script.py"), it throws an exception as it cannot locate the python script.
What would be the best place to place the python script and how can I access it in the Java class without specifying the complete path. Since I am new to maven, it could be due to the method used to execute the Java program.
package discourse.apps.features;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Test {
protected String scriptPath = "/Users/user1/project1/scripts/script.py";
protected String python3Path = "/Users/user1/.virtualenvs/python3/bin/python3";
public static void main(String[] args) throws IOException {
new Test().score();
}
public JSONObject score() {
String text1="a";
String text2="b";
JSONObject rmap =null;
try
{
String line= null;
String writedir=System.getProperty("user.dir")+ "/Tmp";
String pbCommand[] = { python3Path, scriptPath,"--stringa", text1, "--stringb",text2,"--writedir", writedir };
ProcessBuilder pb = new ProcessBuilder(pbCommand);
Process p = pb.start();
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
JSONParser parser = new JSONParser();
rmap= (JSONObject) parser.parse(line);
}
} catch (IOException | ParseException ioe) {
System.err.println("Error running script");
ioe.printStackTrace();
System.exit(0);
}
return rmap;
}
}
Here is the output from pb command
pbCommand[0]:/Users/user1/.virtualenvs/python3/bin/python3
pbCommand[1]:displays the complete python script
import os,sys
from pyrouge import Rouge155
import json
from optparse import OptionParser
def get_opts():
parser = OptionParser()
parser.add_option("--stringa", dest="str_a",help="First string")
parser.add_option("--stringb", dest= "str_b",help="second string")
parser.add_option("--writedir", dest="write_dir", help="Tmp write directory for rouge")
(options, args) = parser.parse_args()
if options.str_a is None:
print("Error: requires string")
parser.print_help()
sys.exit(-1)
if options.str_b is None:
print("Error:requires string")
parser.print_help()
sys.exit(-1)
if options.write_dir is None:
print("Error:requires write directory for rouge")
parser.print_help()
sys.exit(-1)
return (options, args)
def readTextFile(Filename):
f = open(Filename, "r", encoding='utf-8')
TextLines=f.readlines()
f.close()
return TextLines
def writeTextFile(Filename,Lines):
f = open(Filename, "w",encoding='utf-8')
f.writelines(Lines)
f.close()
def rougue(stringa, stringb, writedirRouge):
newrow={}
r = Rouge155()
count=0
dirname_sys= writedirRouge +"rougue/System/"
dirname_mod=writedirRouge +"rougue/Model/"
if not os.path.exists(dirname_sys):
os.makedirs(dirname_sys)
if not os.path.exists(dirname_mod):
os.makedirs(dirname_mod)
Filename=dirname_sys +"string_."+str(count)+".txt"
LinesA=list()
LinesA.append(stringa)
writeTextFile(Filename, LinesA)
LinesB=list()
LinesB.append(stringb)
Filename=dirname_mod+"string_.A."+str(count)+ ".txt"
writeTextFile(Filename, LinesB)
r.system_dir = dirname_sys
r.model_dir = dirname_mod
r.system_filename_pattern = 'string_.(\d+).txt'
r.model_filename_pattern = 'string_.[A-Z].#ID#.txt'
output = r.convert_and_evaluate()
output_dict = r.output_to_dict(output)
newrow["rouge_1_f_score"]=output_dict["rouge_1_f_score"]
newrow["rouge_2_f_score"]=output_dict["rouge_2_f_score"]
newrow["rouge_3_f_score"]=output_dict["rouge_3_f_score"]
newrow["rouge_4_f_score"]=output_dict["rouge_4_f_score"]
newrow["rouge_l_f_score"]=output_dict["rouge_l_f_score"]
newrow["rouge_s*_f_score"]=output_dict["rouge_s*_f_score"]
newrow["rouge_su*_f_score"]=output_dict["rouge_su*_f_score"]
newrow["rouge_w_1.2_f_score"]=output_dict["rouge_w_1.2_f_score"]
rouge_dict=json.dumps(newrow)
print (rouge_dict)
def run():
(options, args) = get_opts()
stringa=options.str_a
stringb=options.str_b
writedir=options.write_dir
rougue(stringa, stringb, writedir)
if __name__ == '__main__':
run()
pbCommand[2]:--stringa
pbCommand[3]:a
pbCommand[4]:--stringb
pbCommand[5]:b
pbCommand[6]:--writedir
pbCommand[7]:/users/user1/project1/Tmp
Put the script in the main/resources folder it will then be copied to the target folder.
Then make sure you use something like the com.google.common.io.Resources class, which you can add with
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava-io</artifactId>
<version>r03</version>
</dependency>
I then have a class like this which helps to convert resource files to Strings:
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public class FileUtil
{
public static String convertResourceToString(URL url)
{
try
{
return Resources.toString(url, Charsets.UTF_8);
}
catch (Exception e)
{
return null;
}
}
public static String convertResourceToString(String path)
{
return convertResourceToString(Resources.getResource(path));
}
public static String convertResourceToString(URI url)
{
try
{
return convertResourceToString(url.toURL());
}
catch (MalformedURLException e)
{
return null;
}
}
}
Some advice if you are learning maven try using it instead of the IDE to run and package your application, that is what it is suppose to do. Then once you are confident that the application will function as a packaged jar then just use the IDE to run it.
I want to execute a command in the cmd from java. I want to execute link41b.exe in cmd from java. Normally it work like that :
I write the path of the link41b.exe
I execute link41b.exe
I wait until she excute this application and it give me a result .
I write the sentence that I want to link it
For example: linkparser>""the sentence""
So to execute this command I have written this code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
public class tistlink {
public static void main(String[] args) {
Process child;
String line;
try {
String command="cmd /c link41b.exe";
child = Runtime.getRuntime().exec(command);
child.waitFor();
OutputStream out = child.getOutputStream();
PrintStream printStream = new PrintStream(out);
printStream.println(" the girl is beautifull");
System.out.println(child.exitValue());
BufferedReader input =new BufferedReader(new
InputStreamReader(child.getInputStream()));
while((line = input.readLine()) != null)
{System.out.println(line); }
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}}
}
The method exitvalue() returns 1. But it didn't return the result.
What it is the problem of this code because it gave me any error?
I have 3 methods
for open file
for read file
for return things read in method read
this my code :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication56;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author x
*/
public class RemoteFileObjectImpl extends java.rmi.server.UnicastRemoteObject implements RemoteFileObject
{
public RemoteFileObjectImpl() throws java.rmi.RemoteException {
super();
}
File f = null;
FileReader r = null;
BufferedReader bfr = null;
String output = "";
public void open(String fileName) {
//To read file passWord
f = new File(fileName);
}
public String readLine() {
try {
String temp = "";
String newLine = System.getProperty("line.separator");
r = new FileReader(f);
while ((temp = bfr.readLine()) != null) {
output += temp + newLine;
bfr.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
return output;
}
public void close() {
try {
bfr.close();
} catch (IOException ex) {
}
}
public static void main(String[]args) throws RemoteException{
RemoteFileObjectImpl m = new RemoteFileObjectImpl();
m.open("C:\\Users\\x\\Documents\\txt.txt");
m.readLine();
m.close();
}
}
But it does not work.
What do you expect it to do, you are not doing anything with the line you read, just
m.readLine();
Instead:
String result = m.readLine();
or use the output variable that you saved.
Do you want to save it to a variable, print it, write it to another file?
Update: after your update in the comments:
Your variable bfr is never created/initialized. You are only doing this:
r = new FileReader(f);
so bfr is still null.
You should do something like this instead:
bfr = new BufferedReader(new FileReader(f));