Using ProcessBuilder to make a jar file isn't completing - java

I am trying to compile a jar file from within a Java program. When I run the code it starts to build the jar file and saves about 24k of it then the execution just seems to stop and wait (I am using Process.waitFor() and the program isn't finishing its execution). When I force the program to stop the size of the jar file jumps to about 45k. The jar should be about 1300k.
I tried creating a batch file and then calling the batch file with my ProcessBuilder but the same issue occurs. The batch file when run by itself works perfectly.
This is the code I have so far:
public static void buildJar() {
List<String> jarCmdArgs = new ArrayList<>();
jarCmdArgs.add("jar");
jarCmdArgs.add("cvfM");
jarCmdArgs.add(ROOT_DIRECTORY + File.separator + "my_jar.jar");
jarCmdArgs.add(".");
// jarCmdArgs.add("cmd.exe");
// jarCmdArgs.add("/C");
// jarCmdArgs.add(ROOT_DIRECTORY + File.separator + "make_jar.bat");
ProcessBuilder pb = new ProcessBuilder(jarCmdArgs);
pb.directory(new File(SRC_DIR_PATH));
try {
Process p = pb.start();
p.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
This is the contents of the batch file:
//cd to my working dir with all the files to put into the jar
jar cvfM my_jar.jar .

Related

Cannot access and run batch file commands using java class

I have created a java class to execute a batch file that is in my desktop so that the commands in the batch file will be executed too. The problem is that, i keep getting the error:
The filename, directory name, or volume label syntax is incorrect.
The filename, directory name, or volume label syntax is incorrect.
I have checked the .bat name and the directory. It is correct. When i type cmd /c start C:/Users/attsuap1/Desktop, windows explorer opens the desktop tab. However when i type cmd /c start C:/Users/attsuap1/Desktop/DraftBatchFile.bat, it gives the error. My DraftBatchFile.bat is in my desktop.
Here are my java codes:
public class OpenDraftBatchFile{
public OpenDraftBatchFile() {
super();
}
/**Main Method
* #param args
*/
public static void main(String[] args) {
//Get Runtime object
Runtime runtime = Runtime.getRuntime();
try {
//Pass string in this format to open Batch file
runtime.exec("cmd /c start C:/Users/attsuap1/Desktop/DraftBatchFile.bat");
} catch (IOException e) {
System.out.println(e);
}
}
Why is it that the batch file cannot be executed even if the directory is correct? Someone please help me. Thank you so much.
These are the codes in DraftBatchFile.bat
#echo off
echo.>"Desktop:\testing\draft.txt"
#echo Writing text to draft.txt> Desktop:\testing\draft.txt
When i execute the DraftBatchFile.bat by running the java class, i want a draft.txt file to be created in a testing folder that i have created (in desktop).
there is no such thing as desktop:\
Instead try something like this.
#echo off
echo . %userprofile%\Desktop\testing\dblank.txt
#echo Writing text to draft.txt > %userprofile%\Desktop\testing\dblank.txt
You just need to change a directory and create new subdirectory if it not exist. My offer is change .bat file like this:
#echo off
if not exist "%userprofile%\Desktop\testing" mkdir "%userprofile%\Desktop\testing"
echo.>"%userprofile%\Desktop\draft.txt"
#echo Writing text to draft.txt>"%userprofile%\Desktop\draft.txt"
Also you can create .txt file and write in it text through Java code:
File directory = new File(System.getProperty("user.home")+"//Desktop//testing");
if (!directory.exists())
directory.mkdirs();
String content = "Writing text to draft.txt";
File file = new File(System.getProperty("user.home")+"//Desktop//testing//draft.txt");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (writer != null)
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Best way to run a batch (shell / CMD) command in Java / Eclipse?

I have created the following code below in Eclipse / java which executes a batch file, which in turn should also execute once all my TestNG tests have executed but sometimes the bat file will execute and sometimes it dosnt do anything at all, any ideas?
#AfterSuite(alwaysRun = true)
public void executeBatFile() {
try {
List cmdAndArgs = Arrays.asList("cmd", "/c", "copyPasteImgs.bat");
File dir = new File(Paths.get(System.getProperty("user.dir") + "/..").toRealPath() + "\\");
ProcessBuilder pb = new ProcessBuilder(cmdAndArgs);
pb.directory(dir);
Process p = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
}
The batch files moves files from a local folder to a remote folder (When the batch file hasnt worked via eclipse or invoked via jenkins I have manually executed the batch file and it did its jobs, very weird...)
thanks for your help
Apache Commons CLI provides functionalities to handle using command line from java. You can also use the exit value to have an idea about what is going on with your command. For example:
String command = "dir";
CommandLine oCmdLine = CommandLine.parse(command);
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
int iExitValue = oDefaultExecutor.execute(oCmdLine);
} catch (ExecuteException e) {
System.err.println("Execution failed.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("permission denied.");
e.printStackTrace();
}

ProcessBuilder with gunzip does not work

I am trying to run this code which fails with the note:
gzip: /home/idob/workspace/DimesScheduler/*.gz: No such file or directory
The code:
ProcessBuilder gunzipPB = new ProcessBuilder("gunzip", System.getProperty("user.dir") + File.separator + "*");
gunzipPB.inheritIO();
int gunzipProcessExitValue;
try {
gunzipProcessExitValue = gunzipPB.start().waitFor();
} catch (InterruptedException | IOException e) {
throw new RuntimeException("Service " + this.getClass().getSimpleName() + " could not finish creating WHOIS AS Prefix Table", e);
}
logger.info("Finished unzipping radb and ripe files. Process exit value : {}", gunzipProcessExitValue);
Exit value is 1.
Same command in terminal works just fine (the files exist).
What can be the problem?
Thanks.
Ido
EDIT:
After trying to use DirectoryStrem I am getting this exception:
java.nio.file.NoSuchFileException: /home/idob/workspace/DimesScheduler/*.gz
Any idea what can be the problem? The files do exist.
The full code:
ProcessBuilder radbDownloadPB = new ProcessBuilder("wget", "-q", "ftp://ftp.radb.net /radb/dbase/*.db.gz");
ProcessBuilder ripeDownloadPB = new ProcessBuilder("wget", "-q", "ftp://ftp.ripe.net/ripe/dbase/split/ripe.db.route.gz");
radbDownloadPB.inheritIO();
ripeDownloadPB.inheritIO();
try {
int radbProcessExitValue = radbDownloadPB.start().waitFor();
logger.info("Finished downloading radb DB files. Process exit value : {}", radbProcessExitValue);
int ripeProcessExitValue = ripeDownloadPB.start().waitFor();
logger.info("Finished downloading ripe DB file. Process exit value : {}", ripeProcessExitValue);
// Unzipping the db files - need to process each file separately since java can't do the globing of '*'
try (DirectoryStream<Path> zippedFilesStream = Files.newDirectoryStream(Paths.get(System.getProperty("user.dir"), "*.gz"))){
for (Path zippedFilePath : zippedFilesStream) {
ProcessBuilder gunzipPB = new ProcessBuilder("gunzip", zippedFilePath.toString());
gunzipPB.inheritIO();
int gunzipProcessExitValue = gunzipPB.start().waitFor();
logger.debug("Finished unzipping file {}. Process exit value : {}", zippedFilePath, gunzipProcessExitValue);
}
}
logger.info("Finished unzipping ripe and radb DB file");
} catch (InterruptedException | IOException e) {
throw new RuntimeException("Service " + this.getClass().getSimpleName() + " could not finish creating WHOIS AS Prefix Table", e);
}
Thanks...
the *.gz glob is not handled by the gunzip command, but the shell. For example, the shell will translate gunzip *.gz to gunzip a.gz b.gz. Now when you exec through java, you either have to invoke bash to do the globbing for you, or expand the glob in java, since gzip doesn't know how to handle the glob.
Java 7 has new libraries which make expanding glob patterns easier.

Running a .jar with code

I'm trying to run a jar file from code - in a "launcher". The launcher is an applet, which downloads the needed files.
But for some reason, it only works on some computers? I can't seem to make any link between the computers it doesn't work on. Below is my code:
ProcessBuilder pb = new ProcessBuilder(System.getProperty("java.home") + "\\bin\\javaw", "-jar", data_jarToRun, data_authKey);
pb.directory(new File(directory));
try {
pb.start();
window.setStage("Launched!");
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
window.setFailed();
window.setData("Failed to launch!");
}
Note that:
data_jarToRun equals "theJar.jar"
data_authKey is a String that needs to be included in "theJar" arguments.
directory is the folder that "theJar" is found in.

.jar doesn't run external program

So i have a java project made in eclipse with sphinx voice recognition. If i say a certain word then it runs a .bat file.
if (resultText.equals("word")) {
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("C:/c.bat");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In Eclipse it works fine, but after i export the .jar and run it, if i say that specific word, it doesn`t run that .bat. So any ideas why this only runs my .bat file from eclipse and not from command line? Thanks
I am not sure about this but atleast try this solution once.
Try giving the .bat file path as C:\\c.bat and then try again.
Try adding something like:
File f = new File("c:/c.bat");
if(f.exists()) {
// execute the file
Process process = runtime.exec(f.getAbsolutePath());
process.waitFor();
InputStream stdout = process.getInputStream();
InputStream stderr = process.getErrorStream();
// check the streams for errors
} else {
// log error
}
hth

Categories

Resources