How to change directory in java - java

I want to unzip tgz files using 7zip utility in Windows OS. My 7zip.exe file is placed in D: drive. My unzip command is 7z e abc.tgz. This command is working through terminal but not through my java code.
Previously I tried
Runtime r=Runtime.getRuntime();
r.exec("cmd.exe d: ", null, new File("D:\\"));
Process p=r.exec("7z e abc.tgz"null,new File("D:\\"));
InputStream is=p.getInputStream();
BufferedReader br= new BufferedReader(new InputStreamReader(is));
String line=new String();
while ((line=br.readLine())!=null) System.out.println (line);
I even tried this
ProcessBuilder pb = new ProcessBuilder("cmd.exe","/c","start","cmd");
pb = pb.directory(new File("D:"));
pb.command("7z", "e", "abc.tgz");
pb.start();
Is there any different method for changing the directory through java?

You can use this snippet to change the working directory:
String[] command = unzip_your_file;
ProcessBuilder builder = new ProcessBuilder(command);
builder.directory(new File("directory_location"));

Related

how to run vb exe file from java server side with parameters

I am writing a java server process that in addition should run vb.exe file with parameters in windows only.
I tried to use ProcessBuilder with start function and Process with exec function but I have no error but nothing happens!
the cmd for example:
"C:\AL500\BIAFLABEL\AddToQueue.exe" "C:\AL500\BiafLabel\Templates\2.xml" -printer \\mickaelbpc\System-N
the command line definitions in the code:
String fullcmd = "\"C:\\AL500\\BIAFLABEL\\AddToQueue.exe\" \"C:\\AL500\\BiafLabel\\Templates\\2.xml\" -printer \\\\mickaelbpc\\System-N";
String fullcmd1 = "C:\\AL500\\BIAFLABEL\\AddToQueue.exe C:\\AL500\\BiafLabel\\Templates\\2.xml -printer \\\\mickaelbpc\\System-N";
String cmd1 = "C:\\AL500\\BIAFLABEL\\AddToQueue.exe";
String cmd2 = "C:\\AL500\\BiafLabel\\Templates\\2.xml";
String cmd3 = "-printer";
String cmd4 = "\\\\mickaelbpc\\System-N";
String[] command = new String[]{cmd1, cmd2, cmd3,cmd4};
Process + array:
File dir = new File("C:/workspace");
Process process = Runtime.getRuntime().exec(command, null, dir);
process.waitFor();
InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream();
String strData;
StringBuffer sb = new StringBuffer("");
BufferedReader brData = new BufferedReader(new
InputStreamReader(stdout));
while ((strData = brData.readLine()) != null)
{
sb = sb.append(strData).append("\r\n");
}
brData.close();
ProcessBuilder + string command with ":
ProcessBuilder pb=new ProcessBuilder(fullcmd);
pb.redirectErrorStream(true);
Process process1=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process1.getInputStream()));
String line;
while (true) {
line = inStreamReader.readLine();
if (line == null) { break; }
System.out.println(line);
ProcessBuilder + string command with no ":
File log = new File("log");
ProcessBuilder pb=new ProcessBuilder(/*command*/fullcmd1);
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.appendTo(log));
Process process1=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process1.getInputStream()));
String line;
while (true) {
line = inStreamReader.readLine();
if (line == null) { break; }
System.out.println(line);
}
after the changes I am getting this error: "java.io.IOException: Cannot run program "C:\AL500\BIAFLABEL\AddToQueue.exe C:\AL500\BiafLabel\Templates\2.xml -printer \mickaelbpc\System-N": CreateProcess error=2, The system cannot find the file specified" can you please advise?
ProcessBuilder with cmd.exe:
ProcessBuilder pb=new ProcessBuilder("cmd.exe","/c",fullcmd);
pb.redirectErrorStream(true);
Process process1=pb.start();
BufferedReader inStreamReader = new BufferedReader(
new InputStreamReader(process1.getInputStream()));
String line;
while (true) {
line = inStreamReader.readLine();
if (line == null) { break; }
System.out.println(line);
}
I did all the options and more...if it will be necessary I will add more examples
the vb exe should print a file. any idea how to run it from java process? or what is wrong with my code?
Study the error and output stream of the command. Need to redirect them and stream them in a separate thread. Or try this fronm
File log = new File("log");
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.appendTo(log));
Is the full path correct? Can you print the commad line space seperated to a file called run.cmd and run that manually and see what happens from prompt?
which directory are you starting the process from might have to be different than the one that your java program is running at? Process builder has a https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html#directory()
To know which directory your java program is using do this:
File f = new File("./");
try{
System.out.println("Start dir is :" + f.getCanonicalFile());
}catch...
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#getCanonicalFile()
i do not think you do not need to add quotes, just set them in the array with actual values. but if running from a .cmd you will need to qualify params with spaces by putting quotes. best to have no spaces in the paths or params when testing.
See github.com/tgkprog/nli/blob/master/RunCmd.java if ur redirecting to log, dont get the stream again in your loop. and dont call via cmd.exe. in my example ignore the actual commmand, put ur exe and params, i just called a sh file as on ubuntu. You call with your 4 params

Run exec file using Java on Mac

I need to start a server using bash, so I had created an UNIX shell , but I am not able to execute it with Java from Eclipse.
I tried the following code which doesn't work :
Process proc = Runtime.getRuntime().exec(./startServer);
Here is content of the startServer file :
#!/bin/bash
cd /Users/sujitsoni/Documents/bet/client
npm start
You can try the following two options.
Option 1
Process proc = Runtime.getRuntime().exec("/bin/bash", "-c", "<Abosulte Path>/startServer");
Option 2
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "<Absolute Path>/startServer");
pb.directory(new File("<Absolute Path>"));
Process proc = pb.start();
A couple Of things can go wrong:
The path to the file you have given might be wrong for eclipse it can take relative path but from the command line, it will take the absolute path.
error=13, Permission denied - If the script file doesn't have required permissions. In your scenario, that might not the case as you are not getting any error.
At last, you are executing the script by java program so the output of your script will not be printed out. In your scenario, this might be the case. You need to capture the output of script from BufferedReade and print it. ( In your case server might have started but you are not seeing the logs/output of the script.
See the code sample below for printing output.
public static void main(String[] args) throws IOException, InterruptedException {
Process proc = Runtime.getRuntime().exec("./startServer");
proc.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output);
}

java exec attempting to untar a file

I have been trying to untar a .tbz file without a lot of success in a java app. I have now decided to try and hit the command line to get the job done, and it currently doesn't through any errors but it doesn't untar the file, either. Can anyone see an issue with this?
String[] cmd = { "tar", "-xjf", "/var/tmp/filename.tbz"};
Process p =Runtime.getRuntime().exec(cmd, null);
EDIT, this works:
List<String> commands = new ArrayList<String>();
commands.add("tar");
commands.add("-xvjf");
commands.add("/var/tmp/filename.tbz");
ProcessBuilder pb = new ProcessBuilder(commands);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String readline;
while ((readline = reader.readLine()) != null) {
System.out.println(readline);
}
What is a cd command doing there in the middle? Perhaps you meant this:
String[] cmd = { "tar", "-xjf", "/var/tmp/filename.tbz"};
If instead of the above, you really want to do this:
cd /var/tmp
tar -xjf filename.tbz
In this case you can use ProcessBuilder.

Java ProcessBuilder: OutputStream(Reader) of a process never gets ready() for *certain* commands

I've written an interface to call shell commands from Java for testing purposes. For a few commands, that works quite fine, but for others, the OutputStream of the process never gets ready(). Does anyone have an explanation ? I give the full code:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.err.print("cmd: ");
String line=in.readLine();
The following are all fine for "cat -n", not for "sed s/a/e/"
ProcessBuilder pb = new ProcessBuilder(Arrays.asList(("bash -c \""+line+"\"").split(" ")));
// ProcessBuilder pb = new ProcessBuilder(Arrays.asList(("cmd /C "+line).split(" ")));
// ProcessBuilder pb = new ProcessBuilder("cmd","/C",line);
// ProcessBuilder pb = new ProcessBuilder("bash","-c",line);
// ProcessBuilder pb = new ProcessBuilder(Arrays.asList(line.split(" ")));
Interaction with the process:
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedWriter toP = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
BufferedReader fromP = new BufferedReader(new InputStreamReader(p.getInputStream()));
for(line = in.readLine(); line!=null; line=in.readLine()) {
toP.write(line+"\n");
toP.flush();
System.err.println("stdin: \""+line+"\"");
while(!fromP.ready()); // sed hangs, cat doesn't
System.out.println("result: \""+fromP.readLine()+"\"");
}
One can find plenty of information on ProcessBuilder issues, and for most of them, wrapping stdin and stdout into different Threads seems to be a solution. But if indeed this is the solution, then why ?
An further: Does anyone have an explanation why the straight-forward approach fails and under what circumstances this occurs ? From the example, I can rule out that it is the way the arguments are presented or the specific shell (cmd/bash).
I'm working with Java 1.6 on a Windows7 machine with Cygwin installed, hence both bash and cmd. Could that be a Cygwin issue ?

bat file does not start and bat file is in a folder

I am trying to launch a bat file. The bat file is in a folder. The folder contains all the executable jar file. I tried this code to launch the bat file but unable.
ProcessBuilder pb = new ProcessBuilder( "C:\\Users\\user\\Desktop\\NetBeansProjects\\Genomic DataWarehouse Project\\biodwh.startBioDWH.bat" );
pb.redirectErrorStream(true);
Process p = pb.start();
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader( is ) );
for ( String line = br.readLine(); line != null; line = br.readLine() )
{
System.out.println( ">" + line );
}
p.waitFor();
try use this Runtime.getRuntime().exec("cmd /c start C:\Users\user\Desktop\NetBeansProjects\Genomic DataWarehouse Project\biodwh.startBioDWH.bat");
in your .bat add the line pushd %~dp0
this will change the current drive and path to the one of the bat file.
Ok, seems I misunderstood the question.
I think you can't execute batch files directly but need to launch it using cmd.exe. Try adding cmd /c (with a space at the end) to your new ProcessBuilder line :
ProcessBuilder pb = new ProcessBuilder( "cmd /c C:\\Users\\user\\Desktop\\NetBeansProjects\\Genomic DataWarehouse Project\\biodwh.startBioDWH.bat" );
Or ou can try to execute the bat file this way :
String path="C:\\Users\\user\\Desktop\\NetBeansProjects\\Genomic DataWarehouse Project\\";
File dir = new File(path);
Process process = Runtime.getRuntime().exec("cmd /c "+path+"biodwh.startBioDWH.bat", null, dir);
Or you can make it shorter if you don't need the batch file to be executed from the folder where it resides
Process process = Runtime.getRuntime().exec("cmd /c C:\\Users\\user\\Desktop\\NetBeansProjects\\Genomic DataWarehouse Project\\biodwh.startBioDWH.bat");

Categories

Resources