So I am still learning programming, I am creating a simple application that can backup a database but the problem is when I click the button for backup, nothing happens, it does not even display the "can't create backup". I am using xampp, in case that is relevant. I have zero idea as to why is it is not working, and I am really curios what is the reason behind it, any help will be greatly appreciated.
...
String path = null;
String filename;
//choose where to backup
private void jButtonLocationActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
String date = new SimpleDateFormat("MM-dd-yyy").format(new Date());
try {
File f = fc.getSelectedFile();
path = f.getAbsolutePath();
path = path.replace('\\', '/');
path = path+"_"+date+".sql";
jTextField1.setText(path);
} catch (Exception e) {
e.printStackTrace();
}
}
//backup
private void jButtonBackUpActionPerformed(java.awt.event.ActionEvent evt) {
Process p = null;
try{
Runtime runtime = Runtime.getRuntime();
p=runtime.exec("C:/xampp/mysq/bin/mysqldump -u root --add-drop-database -B capstone -r "+path);
int processComplete = p.waitFor();
if (processComplete==0) {
jLabel1.setText("Backup Created Success!");
} else {
jLabel1.setText("Can't create backup.");
}
} catch (Exception e) {
}
}
You use a try-catch block in the jButtonBackUpActionPerformed, but the catch statement is empty. Therefore, if an exception is raised for whatever reason, no file would be written and you would get no output. You can try to use e.printStackTrace() like in the catch statement of the other button for debugging.
I found the underlying problem, thanks to stan. It was a typo problem, instead of "mysql", I have put "mysq" thank you guys!
java.io.IOException: Cannot run program "C:/xampp/mysq/bin/mysqldump.exe": CreateProcess error=2, The system cannot find the file specified
this will run any shell script on Linux server. Test it on windows ... shoud work too
public static int executeExternalScript(String path) throws InterruptedException, IOException {
ProcessBuilder procBuilder = new ProcessBuilder(path);
procBuilder.redirectErrorStream(true);
Process process = procBuilder.start();
BufferedReader brStdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = brStdout.readLine()) != null) { logger.info(line); }
int exitVal = process.waitFor();
brStdout.close();
return exitVal;}
Related
I am using ffmpeg to combine two mp4 files without including their audio; however, despite following the formatting in many other posts, I'm unable to get my code to function.
//public variables
public void test(){
String canonicalPath = new File(".").getCanonicalPath();
String ffmpegPath="/usr/bin/local/ffmpeg";
String vidSectPath=canonicalPath.concat("/src/Video-Sections");
String vidPath=canonicalPath.concat("/src/Videos");
String tempA=vidSectPath+"/Earth.mp4";
String tempB=vidSectPath+"/Waves.mp4";
String tempVidPath=vidPath+"/tvp.mp4";
String[]cmd1={ffmpegPath,"-i",tempA,"-i",tempB,"-filter_complex","[0:0][1:0]concat=n=2:v=1:a=0[out]","-map","[out]",tempVidPath};
ProcessBuilder pb = new ProcessBuilder(cmd1);
boolean exeCmdStatus = executeCMD(pb);
}
private boolean executeCMD(ProcessBuilder pb)
{
pb.redirectErrorStream(true);
Process p = null;
try {
p = pb.start();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("oops");
p.destroy();
return false;
}
// wait until the process is done
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("woopsy");
p.destroy();
return false;
}
return true;
}
I get a new mp4 file after running this code, but the mp4 file has 0 bytes and can't be opened in any media player. I've tried adding "-pix_fmt yuv420p" to cmd1, but this doesn't seem to help in any way.
I've also tried using the concat demuxer method by making the cmd1 string[] variable equal to:
ffmpegPath,"-f","concat","-i","-safe","0","/Users/JL/Documents/workspace/VidTest/src/concat.txt","-vcodec","copy",tempVidPath};
In which the content of concat.txt is
file '/Users/JL/Documents/workspace/VidTest/src/Video-Sections/Earth.mp4'
file '/Users/JL/Documents/workspace/VidTest/src/Video-Sections/MovWaves.mp4'
However, this method doesn't seem to be able to create the concatenated mp4 file.
I'm not sure what is wrong with my code. I'm also using a mac to execute the code.
I have a problem with my Java program where I have a button that opens the command prompt and opens a batch file to run a series of commands. To do this, I need to change directory.
Here is my code:
private void CommandPromptButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
new java.lang.ProcessBuilder("cmd.exe").start();
java.lang.Runtime.getRuntime().exec(new String[]{
//I need to change the directory in command prompt and I do not want to use escape
"cmd.exe","/c","start","cd C:\Users\Faz"
});
} catch (IOException ex) {
Logger.getLogger(TMISGUIInstallerPage.class.getName()).log(Level.SEVERE, null, ex);
}
}
Any suggestions and advice are appreciated.
The following code should work
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"C:\\Users\\Faz\" && dir");
You could change the directory in the ProcessBuilder using the ProcessBuilder#directory() and then start the process. Here is a sample code:
ProcessBuilder start = new ProcessBuilder("cmd.exe", "/c", "start");
start.directory(new File("C:\\Users"));
start.start();
Upvoted Aukta's answer, it should solve your problem.
But as you asked:
To do this, I need to change directory.
Actually with ProcessBuilder and its directory(File directory), we can easily set the working directory. Here is a simple demo to list all files in a specified directory to show you how it can be used.
public static void main(String... args) {
ProcessBuilder processBuilder = new ProcessBuilder("ls"); // pass in your command and options;
processBuilder.directory(new File("/home")); // specify you directory here;
try {
Process process = processBuilder.start();
String line = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
The output:
gitlab-runner
hearen
ubuntu
Thanks for all of your help and suggestions. I have finally found an answer. I forgot to add that I tried using Java runtime but that does not run all commands. I have found that if I add another quotation mark, I can change the directory.
private void CommandPromptButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
new java.lang.ProcessBuilder("cmd.exe").start();
java.lang.Runtime.getRuntime().exec(new String[]{
//I need to change the directory in command prompt and I do not want to use escape
"cmd.exe","/c","start","cd C:\"Users\"Faz"
});
} catch (IOException ex) {
Logger.getLogger(TMISGUIInstallerPage.class.getName()).log(Level.SEVERE, null, ex);
}
}
Thank you for all of your help. Probs submit some more questions later. Cheers!
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
I made this code to move a folder then hardlink it to it's original destination. The problem it works fully when I'm just trying it from eclipse but when I make it into it's own self executing jar it wont create the hardlink but it will move the folder. The code runs a command line and then enters the commands. I dont know ehy the move command works and not the other one. Please help.
(Mklink command)
import java.io.*;
import javax.swing.JOptionPane;
public class The_Cloud_Setup {
public static void main(String[] args) throws IOException
{
try {
String command = "c:\\cmd.exe";
Runtime.getRuntime().exec(command);
}
catch (IOException e){
JOptionPane.showMessageDialog(null , e.getMessage(), "End Result", 2);
System.err.println(e.getMessage());
}
String[] StringMove = { "cmd.exe", "/c", "move"+" "+"\"C:/Users/%username%/Documents/My Games/Terraria/Players\""+" "+"\"C:/Users/%username%/Google Drive/Players\""};
String[] StringMklink = {"cmd.exe", "/c", "mklink"+" "+"/d"+" "+"\"C:/Users/%username%/Documents/My Games/Terraria/Players\""+" "+"\"C:/Users/%username%/Google Drive/Players\""};
Process ProcessMove = Runtime.getRuntime().exec(StringMove);
Process ProcessMklink = Runtime.getRuntime().exec(StringMklink);
BufferedReader VarMove = new BufferedReader(new InputStreamReader(ProcessMove.getInputStream()));
BufferedReader VarMklink = new BufferedReader(new InputStreamReader(ProcessMklink.getInputStream()));
String temp = "";
while ((temp = VarMove.readLine()) != null) {
System.out.println(temp);
}
VarMove.close();
VarMklink.close();
}
}
Most likely, when you are running natively, the move command has not completed before your program attempts to execute the mklink command. You can't make a link where there is an existing folder.
I want to create diff of two files. I tried searching for code in Java that does it, but didnt find any simple code/ utility code for this. Hence, I thought if I can somehow run linux diff/sdiff command from my java code and make it return a file that stores the diff then it would be great.
Suppose there are two files fileA and fileB. I should be able to store their diff in a file called fileDiff through my java code. Then fetching data from fileDiff would be no big deal.
You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.
For example, here's a complete program that will showcase how to do it:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class testprog {
public static void main(String args[]) {
String s;
Process p;
try {
p = Runtime.getRuntime().exec("ls -aF");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
}
When compiled and run, it outputs:
line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0
as expected.
You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).
If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.
You can also write a shell script file and invoke that file from the java code. as shown below
{
Process proc = Runtime.getRuntime().exec("./your_script.sh");
proc.waitFor();
}
Write the linux commands in the script file, once the execution is over you can read the diff file in Java.
The advantage with this approach is you can change the commands with out changing java code.
You need not store the diff in a 3rd file and then read from in. Instead you make use of the Runtime.exec
Process p = Runtime.getRuntime().exec("diff fileA fileB");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
try to use unix4j. it s about a library in java to run linux command. for instance if you got a command like:
cat test.txt | grep "Tuesday" | sed "s/kilogram/kg/g" | sort
in this program will become:
Unix4j.cat("test.txt").grep("Tuesday").sed("s/kilogram/kg/g").sort();
You can call run-time commands from java for both Windows and Linux.
import java.io.*;
public class Test{
public static void main(String[] args)
{
try
{
Process process = Runtime.getRuntime().exec("pwd"); // for Linux
//Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line=reader.readLine())!=null)
{
System.out.println(line);
}
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
process.destroy();
}
}
}
Hope it Helps.. :)
Runtime run = Runtime.getRuntime();
//The best possible I found is to construct a command which you want to execute
//as a string and use that in exec. If the batch file takes command line arguments
//the command can be constructed a array of strings and pass the array as input to
//the exec method. The command can also be passed externally as input to the method.
Process p = null;
String cmd = "ls";
try {
p = run.exec(cmd);
p.getErrorStream();
p.waitFor();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
}finally{
p.destroy();
}
The suggested solutions could be optimized using commons.io, handling the error stream, and using Exceptions. I would suggest to wrap like this for use in Java 8 or later:
public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException {
try {
return execute(command, 0, null, false);
} catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
return execute(command, 0, null, true);
}
public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException {
Process process = new ProcessBuilder().command("bash", "-c", command).start();
if(timeUnit != null) {
if(process.waitFor(timeout, timeUnit)) {
if(process.exitValue() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
} else {
if(destroyOnTimeout) process.destroy();
throw new ExecutionTimeoutException("Execution timed out: " + command);
}
} else {
if(process.waitFor() == 0) {
return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8);
} else {
throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8));
}
}
}
public static class ExecutionFailedException extends Exception {
private static final long serialVersionUID = 1951044996696304510L;
private final int exitCode;
private final List<String> errorOutput;
public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) {
super(message);
this.exitCode = exitCode;
this.errorOutput = errorOutput;
}
public int getExitCode() {
return this.exitCode;
}
public List<String> getErrorOutput() {
return this.errorOutput;
}
}
public static class ExecutionTimeoutException extends Exception {
private static final long serialVersionUID = 4428595769718054862L;
public ExecutionTimeoutException(final String message) {
super(message);
}
}
if the opening in windows
try {
//chm file address
String chmFile = System.getProperty("user.dir") + "/chm/sample.chm";
Desktop.getDesktop().open(new File(chmFile));
} catch (IOException ex) {
Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
{
JOptionPane.showMessageDialog(null, "Terjadi Kesalahan", "Error", JOptionPane.WARNING_MESSAGE);
}
}
ProcessBuilder processBuilder = new ProcessBuilder();
// -- Linux --
// Run a shell command
processBuilder.command("bash", "-c", "ls /home/kk/");
// Run a shell script
//processBuilder.command("path/to/hello.sh");
// -- Windows --
// Run a command
//processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\kk");
// Run a bat file
//processBuilder.command("C:\\Users\\kk\\hello.bat");
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
System.exit(0);
} else {
//abnormal...
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}