How to Run PKZIP From Java
When writing Java code, you often need to invoke other programs for functions not implemented by your own code. Often, the external programs or applications being invoked are not written in Java. Sometimes, you do not even have access to their source codes. You need a way of invoking other Windows applications from Java code. That entails providing input to them, passing control to them in the execution environment they expect, and having access to their output. In particular, it is easy to invoke the PKZIP file compression/decompression utility from Java on Windows.
Things You'll Need
- Computer running Windows
- Java virtual machine and bytecode compiler installed on the computer
- PKZIP installed on the computer
Instructions
-
-
1
Import "java.io.*" and "java.util.*" in your Java code.
-
2
You will run PKZIP in the same runtime context where your Java application is running, but as a separate process. That means that your Java code will create a new process running PKZIP, then wait until the new process is done, then resume executing. For this, first include
Runtime myruntime = Runtime.getRuntime();
in your code.
-
-
3
Include
Process newproc = myruntime.exec("\"c:/program files/pkware/pkzipc.exe\"");
in your code in order to create and fork the new process. The version of PKZIP designed to be invoked from the command line is called "pkzipc.exe".
-
4
Wait until PKZIP is done by including
newproc.waitFor();
-
5
If you want to pass arguments to PKZIP, pass a String array as the argument to the Runtime.exec() method, as shown. The first string must contain the path to, and name of, the executable. The second and subsequent strings contain the arguments. See the PKZIP 6.0 Command Line User's Manual for an extensive explanation of how you can do this by passing arguments to PKZIP. For example, say that we want to add the file named "summary.doc" to the already existing archive named "JanuarySales.zip". Invoke Runtime.exec() this way:
String[] commandwithargs = {
"\"c:/program files/pkware/pkzipc.exe\"",
"-a JanuarySales.zip",
"summary.doc"
};
myruntime.exec(commandwithargs);
-
1
Tips & Warnings
All paths passed to the Runtime.exec() method must be fully specified on Windows. The example above assumes that both "JanuarySales.zip" and "summary.doc" are in the current directory for the Java application's runtime environment. If they are not, prepend the paths for them within the argument to Runtime.exec()
References
- Photo Credit coffee in coffee image by Maria Brzostowska from Fotolia.com