I am currently learning java and I encountered this problem. I am not sure if it can be done like this as I am still in the learning stage. So in my java main coding:
import java.io.File;
import java.io.IOException;
public class TestRun1
{
public static void main(String args[])
{
//Detect usb drive letter
drive d = new drive();
System.out.println(d.detectDrive());
//Check for .raw files in the drive (e.g. E:\)
MainEntry m = new MainEntry();
m.walkin(new File(d.detectDrive()));
try
{
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("cmd /c start d.detectDrive()\\MyBatchFile.bat");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
The "cmd /c start d.detectDrive()\MyBatchFile.bat" does not work. I do not know how to replace the variable.
And i created a batch file (MyBatchFile.bat):
#echo off
set Path1 = d.detectDrive()
Path1
pause
set Path2 = m.walkin(new File(d.detectDrive()))
vol231.exe -f Path2 imageinfo > Volatility.txt
pause
exit
It does not work. Please do not laugh.
I really isn't good in programming since I just started on java and batch file. Can anyone help me with it? I don't want to hard code it to become a E: or something like that. I want to make it flexible. But I have no idea how to do it. I sincerely ask for any help.
Procedure:
You should append the return value of the method which detects the drive, to the filename and compose the proper Batch command string.
Steps:
Get the return value of the method
String drive = d.detectDrive();
so, drive contains the value E:
append the value of drive to the filename
drive+"\MyBatchFile.bat"
so, we have E:\MyBatchFile.bat
append the result the batch command
cmd /c start "+drive+"\MyBatchFile.bat
result is cmd /c start E:\MyBatchFile.bat
So to invoke the batch command, the final code should be as follows:
try {
System.out.println(d.detectDrive());
Runtime rt = Runtime.getRuntime();
String drive = d.detectDrive();
// <<---append the return value to the compose Batch command string--->>
Process p = rt.exec("cmd /c start "+drive+"\\MyBatchFile.bat");
}
catch (IOException e) {
e.printStackTrace();
}
Related
Am trying to get a series of commands on git bash one after the other. I can open the terminal through the code but after that wasn't successful with entering anything. For instance this is the code I tried
String [] args = new String[] {"C:\\Program Files\\Git\\git-bash.exe"};
String something="hi how are you doing";
try {
ProcessBuilder p = new ProcessBuilder();
var proc = p.command(args).start();
var w = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
w.write(something);
} catch (IOException ioException){
System.out.println(ioException);
}
Please let know how to be able to do enter a series of commands into git bash through the code.
The problem is that the command git-bash.exe opens the terminal window but the window's input is still the keyboard, so trying to write to the OutputStream that is returned by method getOutputStream(), in class Process does nothing. Refer to this question.
As an alternative, I suggest using using ProcessBuilder to execute a series of individual git commands. When you do that, your java code gets the command output.
Here is a simple example that displays the git version.
import java.io.IOException;
public class ProcBldT4 {
public static void main(String[] args) {
// C:\Program Files\Git\git-bash.exe
// C:\Program Files\Git\cmd\git.exe
ProcessBuilder pb = new ProcessBuilder("C:\\Program Files\\Git\\cmd\\git.exe", "--version");
pb.inheritIO();
try {
Process proc = pb.start();
int exitStatus = proc.waitFor();
System.out.println(exitStatus);
}
catch (IOException | InterruptedException x) {
x.printStackTrace();
}
}
}
When you run the above code, the git version details will be written to System.out.
Also, if the git command fails, the error details are written to System.err.
You need to repeat the code above for each, individual git command that you need to issue.
I am writing a java code that has the purpose of opening a URL on youtube using Google Chrome but I have been unsuccessful in understanding either method. Here is my current attempt at it.
import java.lang.ProcessBuilder;
import java.util.ArrayList;
public class processTest
{
public static void main(String[] args)
{
ArrayList<String> commands = new ArrayList<>();
commands.add("cd C:/Program Files/Google/Chrome/Application");
commands.add("chrome.exe youtube.com");
ProcessBuilder executeCommands = new ProcessBuilder( "C:/WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe", "cd C:/Program Files/Google/Chrome/Application", "chrome.exe youtube.com");
}
}
It compiles OK, but nothing happens when I run it. What is the deal?
As stated by Jim Garrison, ProcessBuilder's constructor only executes a single command. And you do not need to navigate through the directories to reach the executable.
Two possible solutions for your problem (Valid for my Windows 7, be sure to replace your Chrome path if neccesary)
With ProcessBuilder using constructor with two parameters: command, argument (to be passed to command)
try {
ProcessBuilder pb =
new ProcessBuilder(
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
"youtube.com");
pb.start();
System.out.println("Google Chrome launched!");
} catch (IOException e) {
e.printStackTrace();
}
With Runtime using method exec with one parameter, a String array. First element is the command, following elements are used as arguments for such command.
try {
Runtime.getRuntime().exec(
new String[]{"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
"youtube.com"});
System.out.println("Google Chrome launched!");
} catch (Exception e) {
e.printStackTrace();
}
you shoule invoke start method to execute the operation, like this:
ProcessBuilder executeCommands = new ProcessBuilder( "C:/WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe", "cd C:/Program Files/Google/Chrome/Application", "chrome.exe youtube.com");
executeCommands.start();
I've been struggling for a while now with this problem and i can't seem to fix it. i have tried ProcessBuilder for executing the custom command on linux terminal but its not working
Actually i have two .sh file setProto.sh and setTls.sh file which is used to set the environment.So for executing the command i need to run these two file first for each instance of linux terminal.Only then we can be able to run the custom command anloss on the same instance of linux terminal in which .sh file supposed to run.For some reason i'm not able to make it work what is the mistake in my code ? Here's the code.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ProcessBuilder.Redirect;
public class EngineTest {
public static void main(String[] args) {
try {
ProcessBuilder builder = new ProcessBuilder(
"/. setProto.sh",
"/. setTls.sh",
"/anloss -i ${TOOL_INPUT}/census_10000_col5.csv -d ${TOOL_DEF}/attr_all_def.txt -q k=14,dage=2 -g ${TOOL_RES}/census_100_col8_gen.csv");
builder.directory(new File(System.getenv("HOME") + "/PVproto/Base"));
File log = new File("log");
builder.redirectErrorStream(true);
builder.redirectOutput(Redirect.appendTo(log));
Process process = builder.start();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = "";
String output = "";
while ((line = bufferedReader.readLine()) != null) {
output += line + "\n";
}
System.out.println(output);
int exitValue = process.waitFor();
System.out.println("\n\nExit Value is " + exitValue);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Process does not by default execute in the context of a shell; therefore your shell scripts cannot be executed the way you tried.
ProcessBuilder pb =
new ProcessBuilder( "/bin/bash",
"-c",
". setProto.sh && . setTls.sh && /anloss -i ${TOOL_INPUT}/census_10000_col5.csv -d ${TOOL_DEF}/attr_all_def.txt -q k=14,dage=2 -g ${TOOL_RES}/census_100_col8_gen.csv" );
I am not sure about /anloss - it's unusual for a command to be in root's home /. (Also, the /. you had there in front of the shell scripts - what should they achieve?)
Later
Make sure to replace /anloss with an absolute pathname or a relative pathname relative to $HOME/PVproto/Base, e.g., if it is in this directory, use ./anloss, if it is in $HOME/PVproto/Base/SomeSub, use SomeSub/anloss, etc.
Also, if setProto.sh and . setTls.sh are not in $HOME/PVproto/Base, use an appropriate absolute or relative pathname. If they are, use ./setProto.sh and ./setTls.sh to avoid dependency on the setting of environment variable PATH.
I think you need to use Runtime.exec() for executing the commands on linux. I suppose you are executing your java code on linux machine where linux scripts needs to be run.
Below code snippet will help you in resolving it.
Process process = Runtime.getRuntime().exec(scriptWithInputParameters);
int exitCode = process.waitFor();
if (exitCode == 0) {
System.out.println("Executed successfully");
}
else {
System.out.println("Failed ...");
}
Please note you need to handle error and output stream in different threads to avoid buffer overflow.
If the above works for you then this article will help you further
On clicking a button in a jsp page, I want to run a batch file. I wrote this code to execute a batch file inside a method, but it's not working. Plz help me out.
public String scheduler() {
String result=SUCCESS;
try {
Process p = Runtime.getRuntime().exec("cmd /c start.bat", null, new File("C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\start"));
System.out.println("manual scheduler for application.."+p);
} catch(Exception e) {
}
}
Add this code,
batFile.setExecutable(true);
//Running bat file
Process exec = Runtime.getRuntime().exec(PATH_OF_PARENT_FOLDER_OF_BAT_SCRIPT_FILE+File.separator+batFile.getName());
byte []buf = new byte[300];
InputStream errorStream = exec.getErrorStream();
errorStream.read(buf);
logger.debug(new String(buf));
int waitFor = exec.waitFor();
if(waitFor==0) {
System.out.println("BAT script executed properly");
}
According to this, the following code should work (just remove the cmd /c):
public String scheduler() {
String result=SUCCESS;
try {
File f = new File("C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\start")
Process p = Runtime.getRuntime().exec("start.bat", null, f);
System.out.println("manual scheduler for application.."+p);
} catch(Exception e) {
}
}
It's not clear here whether you just want to run a bat file or you want to wait for it to run.
// the location where bat file is located is required eg. K:/MyPath/MyBat.bat in my case
// If bat file is in classpath then you can provide direct bat file name MyBat.bat
**Runtime rt = Runtime.getRuntime() ;
Process batRunningProcess= rt.exec("cmd /c K:/MyPath/MyBat.bat");**
// This is to wait for process to complete
//if process is completed then value will be 0
**final int exitVal = lawTab_Indexer.waitFor();**
// This line is not required if you just want to run a bat file and dont want to wait for it to get completed.
I just wanted to run a batch file using java code in win7. I can run .exe files with the code but u know it doesn't work with a batch. Where is the problem? You know even cmd.exe doesn't start with that command. But I can run other exe files, I've tried some. The code is this (with try and catch is that): none of them worked!
Runtime.getRuntime().exec("cmd.exe /c demo.bat");
Runtime.getRuntime().exec("demo.bat");
i tried to do work with process and i wrote the code below. it retuened
java.lang.IllegalThreadStateException:process has not exited
at java.lang.ProcessImpl.exitValue(Native Method)
at Test.Asli.main(Asli.java:38)
this is the code:
try{
Runtime rt = Runtime.getRuntime();
Process proc= rt.exec("C:\\Windows\\System32\\cmd.exe");
int b = proc.exitValue();
// int exitVal = proc.exitValue();
//System.out.println("Process exitValue: " + exitVal);}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Try the following:
String[] cmd = {"cmd.exe", "/c", "demo.bat");
Runtime.getRuntime().exec(cmd);
I always prefer splitting the command and the parameters myself. Otherwise it is done by splitting on space which might not be what you want.
Try this:
Runtime.getRuntime().exec("cmd.exe /c start demo.bat");
Use this:
try {
Process p = Runtime.getRuntime().exec("C:PATH/TO/FILE/yourbatchfile.bat");
} catch(Exception e) {
e.printStackTrace();
}
It even hides the annoying prompt window (if you want that)