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 MyCommand {
public static void main(String[] args) {
String [] commandList = {"/bin/bash","-c", "/home/atul/Desktop/javaprogramm/" , "mkdir newmanisha" , "mkdir newmanisha"};
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec(commandList);
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Trying to execute this but nothing happens . I am using ubuntu 13.10.how to do cd in ubuntu using java program. I have used "-c" but it is not working.
Just replace the commandList related line with the following line. That should work ..
String [] commandList = {"/bin/bash", "-c", "cd /home/atul/Desktop/javaprogramm/ && mkdir newmanisha && mkdir newmanisha"};
Related
An equivalent command for something like this I don't know which is the correct form to call a batch command
def proc =["/bin/sh", "-c","curl https://stackoverflow.com"]
proc.waitFor()
StringBuffer outputStream = new StringBuffer()
proc.waitForProcessOutput(outputStream, System.err)
String output = outputStream.toString()
Why don't you consider using java.net.URL instead?
Sample code is here
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Hello{
public static void main(String []args){
try
{
URL url = new URL("http://stackoverflow.com");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
}
catch (Exception e)
{
System.out.println("error occured");
}
}
}
instead if you want to invoke the curl command from java use the below
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class ShellFromJava {
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);
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) {
testHandler("curl http://stackoverflow.com");
}
static void testHandler(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);
}
}
You can spawn a process from Java:
public class useProcess {
public static void main(String[] args) throws Exception {
String params[] = {"/bin/sh", "-c", "curl", "https://stackoverflow.com"};
Process myProcess = Runtime.getRuntime().exec(params);
myProcess.waitFor();
}
}
I have installed the postgresql database and I have to fire few commands on this database through my java code. But the commands are not executing through java code. If I fire the same commands through command prompt they gets execute. Below is my java code:
package frontend.guifx.pginstallation;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MyMultipleCommandsEx {
public static void main(String a[]) throws InterruptedException{
List<String> commands = new ArrayList<String>();
commands.add("CMD");
commands.add("/c");
commands.add("SET PGPASSWOR=test_admin");
commands.add(psql.exe --dbname=postgres --username=test_admin --port=5433 --command="\"CREATE schema test;\"");
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("C:\\Program Files\\PostgreSQL\\9.5\\bin"));
try {
Process prs = pb.start();
int e = prs.waitFor();
System.out.println("Echo command executed, any errors? " + (e == 0 ? "No" : "Yes"));
System.out.println("Echo Output:\n" + output(prs.getInputStream()));
System.out.println("Error code:"+e);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
How to run multiple mongodb commands from a java code. I need the mongodb commands to get executed in background when i run the java program. This program throws some exception "Exception in thread "main" java.io.IOException: Cannot run program "db.createCollection("employ")": error=2, No such file or directory at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) . . .".
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class try1
{
public static void main(String[] args) throws Exception{
String command ="mongo";
String command1="db.createCollection(\"employ\")";
Process proc = Runtime.getRuntime().exec(command);
Process proc1 = Runtime.getRuntime().exec(command1);
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
BufferedReader reader1 =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line1 = "";
while((line1 = reader1.readLine()) != null) {
System.out.print(line1 + "\n");
}
proc1.waitFor();
}
}
I need to run a set of mongo db commands from the java program. The program works with other terminal commands like "ls"(only single command). But there is problem if we give both command1 and command as "ls". Only one ls command gets executed. If trying with only one mongo db command say, "mongo" command does not get executed completely(program does not terminate). Is it because of "proc.waitFor()".
i got the code. db.eval() function serves my purpose. It works perfectly. :)
"query" is the String which stores the mongodb query.
public void qexecute()
{
try{String query="db.products.insert( { item: "card", qty: 15 } )";
MongoClient mongo = new MongoClient("localhost",27017);
DB db = mongo.getDB("test");
DBCollection collection = db.getCollection(tablename);
db.eval(query);
}
catch(UnknownHostException e){
System.out.println(e);
}
catch (MongoException.DuplicateKey e) {
System.out.println("Exception Caught" + e);
}
}
I strongly recommend to use Mongo Spring Data. You can do that:
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class MongoDBCollection {
public static void main(String args[]) {
try {
//Connect to Database
MongoClient mongoClient = new MongoClient("localhost",27017);
DB db = mongoClient.getDB("myDB");
System.out.println("Your connection to DB is ready for Use::"+db);
//Create Collection
DBCollection linked = db.createCollection("employ",new BasicDBObject());
System.out.println("Collection employ created successfully");
} catch(Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}
I want to run 2 cmd commands consecutively. My purpose here, first compile file(with using cmd command not any other things like Java Compiler API), then run.
compiler.java:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class compiler {
public static void main(String[] args) {
final String dosCommand = "cmd /c java -cp ";
final String classname = "example";
final String location = "D:\\";
try {
final Process process2 = Runtime.getRuntime().exec("cmd /k javac D:\\example.java"); //I used /k to remain.
final Process process = Runtime.getRuntime().exec(dosCommand + location + " " + classname);
final InputStream in = process.getInputStream();
final InputStream in2 = process.getErrorStream();
int ch, ch2;
while ((ch = in.read()) != -1) {
System.out.print((char) ch);
}
while ((ch2 = in2.read()) != -1) {
System.out.print((char) ch2); // read error here
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
example.java:(in D:// path.)
public class example {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
When I run compiler.java it gives
Error: Couldn't find or load main class example
No problem in example.java. When I compile and run this example.java file in cmd it runs correctly.
My problem is to run 2 cmd commands consecutively. Finally, How can I run cmd commands consecutively?. Thanks...
I am trying to run a database import command from a Java program like this:
public class Test {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String[] str = {"imp ASKUL/askul#ASKDB file=askdbinstall.dmp log=askul.log fromuser=askul touser=ASKUL full=N ignore=Y grants=Y indexes=Y;"};
Process pro;
try {
pro = Runtime.getRuntime().exec(str);
} catch (Exception e) {
System.out.println(e);
}
}
}
The error Output is:
java.io.IOException: Cannot run program "imp ASKUL/askul#ASKDB file=askdbinstall.dmp log=askul.log fromuser=askul touser=ASKUL full=N ignore=Y grants=Y indexes=Y;": CreateProcess error=2, The system cannot find the file specified
The file askdbinstall.dmp is present because if I Paster the Same Command in CMD, it is importing the database Dump Quite fine. What is My Mistake?
Added:
From Reimius Suggestion I have also tried this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
public class Tes {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
String [] cmd = {"imp", "ASKUL/askul#ASKDB file=askdbinstall.dmp",
"log=askul.log", "fromuser=askul", "touser=ASKUL",
"full=N ignore=Y grants=Y indexes=Y;"};
Process process = Runtime.getRuntime().exec(cmd);
InputStream in = process.getInputStream();
InputStreamReader ins=new InputStreamReader(in);
BufferedReader br = new BufferedReader(ins);
String data = null;
while ((data = br.readLine()) != null) {
System.out.println(data);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output
run:
BUILD SUCCESSFUL (total time: 3 seconds)
No Import is taking place.
Your import command String is being treated as one single command. Try breaking up the tokens. Also check what is being output from Process#getErrorStream:
String[] str = {"imp", "ASKUL/askul#ASKDB file=askdbinstall.dmp",
"log=askul.log", "fromuser=askul", "touser=ASKUL",
"full=N ignore=Y grants=Y indexes=Y;"};
process = Runtime.getRuntime().exec(str);
BufferedReader in =
new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.err.println(line);
}
Aside: ProcessBuilder make the use of parameter passing easier.