Run An OS Command Using Java?
I want to write a java class that does some Unix system maintenance. In particular, I want to read some data out of a database and then do some calculations to figure out which files in particular can be tarred and zipped. The database part is already handled (in other words, I can identify the files I want to take action on) but I'm not sure how to run an operating system command (e.g. "tar cvzf myfile file1 file2 file3") using java.
Read this:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
%
Similar Messages
-
Running unix command using java shows error
Hi All,
I am trying to run UNIX move command using Java exec method but its throwing error, unable to rename. Here below is the code i am trying to run to move all files from one directory to another directory. source and destination directory exists.
public class Demo
public static void main(String args[])
try
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("mv /home/demo1/* /home/demo2");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
t.printStackTrace();
}if i give "mv /home/demo1 /home/demo2" in exec method, its working, with * character its giving problem.
Please help me in resolving the problem.
Thank youCharacters like *, >, &, |, etc. are interpreted by the command shell--that is by the bash, zsh, etc. programs. When you execute a command with ProcessBuilder or Runtime.exec, you're not going through one of those shells, so their interpretation of those characters is not available.
In your code, the character * is being delivered directly to the mv command (which doesn't think * is anything special), as opposed to being turned into a list of files and directories as it would be when it's interpreted by the shell. The mv command doesn't know anything about the * character being special.
If you want to have those shell interpretations, you need to execute the command through a shell. One example is like so, but a) you'll want to read up on the methods in exec() that take arrays of String, and b) you'll want to read up on ProcessBuilder, and c) you'll need to check your shell's man pages to see the exact syntax and arguments.
runtime.exec("/bin/bash -c 'mv x/* y'"); -
To run a command using java code
hi all,
There is a command
"java -jar selenium-server.jar -interactive"
which i am running through command prompt after going to D:\MyFolder\Examples .
i want to execute this command using java code .please helpsubratjyetki wrote:
please answer in detail or if posible can u give the code for thisThe detail is given in the reference. Why don't you read it?
I could give you the code but it will cost you ?100 per hour. -
I want run some command using java
hi all,
i want run command using java code.
from cell prompt when i run this command 'mysqldump test > /home/DBNAME.sql'
it will create DBNAME.sql file.
but i want to run this command using java code
i tried the following code but it did not work.
is any other way is their?
try {
Runtime.getRuntime().exec("setxkbmap nudi");
} catch(IOException ioe) {
ioe.printStackTrace();
thanks in advance
dayahello,
thanks for replay
i am sorry the above code should be like this.(the above code is working fine)
public class ExportTest{
public ExportTest(){
try {
Runtime.getRuntime().exec("mysqldump test > '/root/DBNAME.sql'");
} catch(IOException ioe) {
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
public static void main(String args[]){
new ExportTest();
}when run above class, it not creating DBNAME.sql file.
when run in command prompt it creating DBNAME.sql
($ mysqldump test > /root/DBNAME.sql)
but i want to run this command from java code, that's way tried to do using above
code, but it won't create DBNAME.sql
is it wrong what i am doing? or any other way?
thanks inadvace
daya -
How can I run Runtime.exec command in Java To invoke several other javas?
Dear Friends:
I met a problem when I want to use a Java program to run other java processes by Runtime.exec command,
How can I run Runtime.exec command in Java To invoke several other java processes??
see code below,
I want to use HelloHappyCall to call both HappyHoliday.java and HellowWorld.java,
[1]. main program,
package abc;
import java.util.*;
import java.io.*;
class HelloHappyCall
public static void main(String[] args){
try
Runtime.getRuntime().exec("java -version");
Runtime.getRuntime().exec("cmd /c java HelloWorld "); // here start will create a new process..
System.out.println("Never mind abt the bach file execution...");
catch(Exception ex)
System.out.println("Exception occured: " + ex);
} [2]. sub 1 program
package abc;
import java.util.*;
import java.io.*;
class HelloWorld
public static void main(String[] args){
System.out.println("Hellow World");
} [3]. Sub 2 program:
package abc;
import java.util.*;
import java.io.*;
class HappyHoliday
public static void main(String[] args){
System.out.println("Happy Holiday!!");
} When I run, I got following:
Never mind abt the bach file execution...
I cannot see both Java version and Hellow World print, what is wrong??
I use eclipse3.2
Thanks a lot..sunnymanman wrote:
Thanks,
But How can I see both programs printout
"Happy Holiday"
and
"Hello World"
??First of all, you're not even calling the Happy Holiday one. If you want it to do something, you have to invoke it.
And by the way, in your comments, you mention that in one case, a new process is created. Actually, new processes are created each time you call Runtime.exec.
Anyway, if you want the output from the processes, you read it using getInputStream from the Process class. In fact, you really should read that stream anyway (read that URL I sent you to find out why).
If you want to print that output to the screen, then do so as you'd print anything to the screen.
in notepad HelloWorld.java, I can see it is opened,
but in Java, not.I have no idea what you're saying here. It's not relevant whether a source code file is opened in Notepad, when running a program. -
Run a shell command using Pl/Sql
hi all
i wonder if anyone knows a way to run a shell command using pl/sql
other than java stored procedure
as it seems not to be working in my case
thanx in advance,
Rashaofcourse not
i sent it once then i've got disconnected from interent then i reconnected
and resend my question so it was sent twice
now i hope you can answer my question !!!
Do you really think when asking twice or more often you will get a quicker answer? -
Spanish characters getting garbled while executing command using Java code
Hi,
I try to execute a command using java code. output of the command contains spanish characters. Few of these characters getting garbled after the command execution.
Runtime r = Runtime.getRuntime();
Process p = null;
String pgm="ipconfig /all";
try
p = r.exec(pgm);
BufferedReader br=new BufferedReader(new InputStreamReader
(p.getInputStream()));
while((val = br.readLine()) != null){ System.out.println(val);
catch (Exception e)
return (null);
I tried to run the code using -Duser.language=es -Duser.region=ES -Dfile.encoding=Cp850, but this did nt help. I could see the outputs properly in command prompt,
If i redirect the output to a text file , it is getting garbled,
Please let me know to solve this issue.884543 wrote:
Hi,
I try to execute a command using java code. output of the command contains spanish characters. Few of these characters getting garbled after the command execution.
Runtime r = Runtime.getRuntime();
Process p = null;
String pgm="ipconfig /all";
try
p = r.exec(pgm);
BufferedReader br=new BufferedReader(new InputStreamReader
(p.getInputStream()));
while((val = br.readLine()) != null){ System.out.println(val);
catch (Exception e)
return (null);
I tried to run the code using -Duser.language=es -Duser.region=ES -Dfile.encoding=Cp850, but this did nt help. I could see the outputs properly in command prompt,
If i redirect the output to a text file , it is getting garbled,
Please let me know to solve this issue.Set the character set to UTF-8 to your InputStreamReader, for More details on usage refer the java api :
http://download.oracle.com/javase/6/docs/api/java/io/InputStreamReader.html -
Running Oracle forms 9i using java plug in 1.4.x
Hi,
i want run my forms (9i) using java plug in 1.4.x? could u plz tel me what are changes i have to do in formsconfig and in other places.Thanks for the reply.
I am using Webutil 1.06 an jacob 1.8 with Oracle forms 9iDS (9.0.2.9 version)
i have gone through, step by step as u said,
but form is not running.. i am able to run the form using java-plug-in (1.4.2.)
but when i am implenting with webutil, form is not running...
as i studied the links given by u, in that webutil is compatible with only from 10g.
if so, which is the compatible webutil version for Oracle forms 9iDS (9.0.2.9 version).
My actual goal is to store a file (it may be .doc, .pdf, .xls, .ppt) in the database and retrieving through forms..
and also suggest me if there is any other ways to do it..
plz suggest me..
Naresh.P -
Execute unix command using java
Hello
Can we execute a unix command using java? If it is how we can execute. Is this affect the performance of the program.
ThanksI tried what you said. But its not working and returning error message,
java.io.IOException: CreateProcess: ls -a error=2
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
If i try this statement,
Runtime.getRuntime().exec("c\windows\notepad");
It is working fine.
Any idea about this.
Plz ........... -
Sudo or su command using java problem
hi im having a bit of trouble with the sudo or su command using java:
e.g.
try { Process myProcess = Runtime.getRuntime().exec("sudo ....ect"); my lil application just crashes ever time i try using this command. i know you usually have to type
password in terminal to get privileges. but since my application needs output of certain commands
i need a way to get round.
i was thinking of trying to input the password some how but im pretty much stuck as to how to do it.
thanks for the helpprometheuzz wrote:
sabre150 wrote:
:-( So I'm dumb?You probably know I wasn't serious, but just for the record: note the smiley when I posted it.:-) of course! When all other tools won't do the job then I use a hammer. -
Creating Tail Command using Java
Hi,
When I was searching for tail command for windows I got site: http://dotnetjunkies.com/WebLog/johnwood/archive/2005/01/05/41694.aspx I think program thay have mentioned is writen in some .NET program.
So I was thinking do we have any class in Java some thing similar to FileSystemWatcher so that I can write tail command using java.
Thanks,
Ram DasVirtual Programmer is in the to share the directory
over the Internet.No, that's a file/web server. :) I see, it's a Microsoft term. -
Hi,
I want to execute a dos command using java but i am geting some runtime execption.
I code i wrote:
================
import java.io.*;
import java.util.*;
public class docCom {
public static Runtime run1 = Runtime.getRuntime();
public static void main(String args[])
try{
BufferedReader in = null;
//Runtime r = Runtime.getRuntime();
String [] commands = {"ftp adas.co.in", "aaaaa", "zzzzz", "cd demo", "hash", "mget aaa.txt"};
Process p = Runtime.getRuntime().exec(commands);
String line = new String();
if (p == null ) {
System.out.println("Could not connect");
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = in.readLine()) != null ) {
System.out.println (line);
catch (IOException io){
System.err.println(io.toString() + "*******" +io);
The purpose of the code it to
1) ftp server adas.co.in
2) provide login and password info
3) then mget a file from server to the local machine.
Error i am geting
java.io.IOException: CreateProcess: "ftp adas.co.in" aaaaa zzzzz "cd demo" hash"mget aaa.txt" error=2*******java.io.IOException: CreateProcess: "ftp adas.co.in" aaaaa zzzzz "cd demo" hash "mget aaa.txt" error=2
Press any key to continue...Cross Post:
http://forum.java.sun.com/thread.jspa?threadID=780815&messageID=4441376#4441376 -
Run shell commands using java program
Hi guys,
I am trying to run shell commands like cd /something and ./command with arguments as follows, but getting an exception that ./command not found.Instead of changing directory using "cd" command I am passing directory as an argument in rt,exec().
String []cmd={"./command","arg1", "arg2", "arg3"};
File file= new File("/path");
try{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd,null,file);
proc.waitFor();
System.out.println(proc.exitValue())
BufferedReader buf = new BufferedReader(new InputStreamReader(proc.getInputStream()));
catch(Exception e)
{e.printStackTrace();
So can anyone please tell me what is wrong with this approach? or is there any better way to do this?
Thanks,
Hardikwarnerja wrote:
What gives you the idea that the process to execute is called "./command"? If this is in Windows, it is "cmd.exe" for example.It does not have to be cmd.exe in Windows. Any executable or .bat file can be executed as long as one either specifies the full path or the executable is in a directory that is in the PATH.
On *nix the file has to have the executable bit set and one either specifies the full path or the executable must be in a directory that is in the PATH . If the executable is a script then if there is a hash-bang (#!) at the start of the first line then the rest of the line is taken as the interpreter to use. For example #!/bin/bash or #!/usr/bin/perl .
One both window and *nix one can exec() an interpreter directly and then pass the commands into the process stdin. The advantage of doing this is that one can change the environment in one line and it remains in effect for subsequent line. A simple example of this for bash on Linux is
import java.io.OutputStreamWriter;
import java.io.Writer;
public class ExecInputThroughStdin
public static void main(String args[]) throws Exception
final Process process = Runtime.getRuntime().exec("bash");
new Thread(new PipeInputStreamToOutputStreamRunnable(process.getErrorStream(), System.err)).start();
new Thread(new PipeInputStreamToOutputStreamRunnable(process.getInputStream(), System.out)).start();
final Writer stdin = new OutputStreamWriter(process.getOutputStream());
stdin.write("xemacs&\n");
stdin.write("cd ~/work\n");
stdin.write("dir\n");
stdin.write("ls\n");
stdin.write("gobbldygook\n"); // Forces output to stderr
stdin.write("echo $PATH\n");
stdin.write("pwd\n");
stdin.write("df -k\n");
stdin.write("ifconfig\n");
stdin.write("echo $CWD\n");
stdin.write("dir\n");
stdin.write("cd ~/work/jlib\n");
stdin.write("dir\n");
stdin.write("cat /etc/bash.bashrc\n");
stdin.close();
final int exitVal = process.waitFor();
System.out.println("Exit value: " + exitVal);
}One can use the same approach with Windows using cmd.exe but then one must be aware of the syntactic differences between commands running in .bat file and command run from the command line. Reading 'help cmd' s essential here.
The class PipeInputStreamToOutputStreamRunnable in the above example just copies an InputStream to an OutputStream and I use
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class PipeInputStreamToOutputStreamRunnable implements Runnable
public PipeInputStreamToOutputStreamRunnable(InputStream is, OutputStream os)
is_ = is;
os_ = os;
public void run()
try
final byte[] buffer = new byte[1024];
for (int count = 0; (count = is_.read(buffer)) >= 0;)
os_.write(buffer, 0, count);
} catch (IOException e)
e.printStackTrace();
private final InputStream is_;
private final OutputStream os_;
} -
Running System Commands using Java
HI,
I am developing an application using java which requires some system commands to be run.For example i have to write a java function which can program the windows scheduler to run a particular executable at some time & another one to initiate an ftp.I however do not know how to execute the corresponding commands from java.Is there any way or some specific api(similar to the system command in c) that i can use to perform these operations.I am using j2sdk 1.4.0_01 on a win 98 machine to develop the application.See [url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html]java.lang.Runtime
-
Running Dos Command using Java
How do i run a particular Dos command using a simple java class?
Process process = Runtime.getRuntime().exec( ... );
Search the forum. There are plenty of examples.
Maybe you are looking for
-
Returns on sales orders regarding contracts
Hi Guys, I have a problem with returns on sales orders. We get returns on sales orders - like most companies. If the sales order has a parent order of the type contract / quantity agreement, the return is increasing the open quantity of the contract.
-
How to clear all fixed assets in SAP Business One
Client wants to clear all fixed assets and create new ones. What is the best way to do it. Thanks.
-
I have two computers - iMac and PC. What is the EARLIEST version of Acrobat I can run on each system. I am running 10.9.2 on iMac and Windows 8 on PC. Thanks.
-
Wage type not showing in net pay payslip
dear all, It has been observed in some cases of full and final settlement where there is a payment to be made in respect of Car Maintenace Reimbursement and Fuel Reimbursement. The amount in respect of both these reimbursements to be entered under In
-
Upgrading but not installing Flash with MSI
I have an environment of some 600 PCs running XP. A few have Flash installed, most do not. Those that have Flash installed are a variety of versions. It's my intent to perform a Flash install using MSI and GPO, and that's (mostly) tested and working.