views:

271

answers:

3

Hi,
I am trying to Compress and Archive all the files in a folder, using Java Runtime class. My code snippet looks as this :

public static void compressFileRuntime() throws IOException, InterruptedException {

    String date = Util.getDateAsString("yyyy-MM-dd");
    Runtime rt = Runtime.getRuntime();
    String archivedFile = "myuserData"+date+".tar.bz2";
    String command = "tar --remove-files -cjvf "+archivedFile+" marketData*";
    File f = new File("/home/amit/Documents/");
    Process pr = rt.exec(command, null, f);
    System.out.println("Exit value: "+pr.exitValue());
}

The above code doesn't archive and compress the file as expected, though it creates a file myuserData2009-11-18.tar.bz2 in the folder "/home/amit/Documents/".

Also the output is

Exit value: 2.

While if I execute the same command from command line, it gives the expected result.

Please tell me what I am missing.

Thanks
Amit

+1  A: 

(not an answer for your question, more of a suggestion) Why not try this instead.

Bozho
For two major reasons I have not tried the above:1. The compression is better in bz2 format. I need to compress the files just once a day.2. I need to delete the files which have been archived, all in one shot.
Amit
+2  A: 

The problem lies in this part:

" marketData*"

you expect the filenames to be compressed to be globbed from the * wildcard. Globbing is done by the shell, not by the tools themselves. your choices are to either:

  • numerate the files to be archived yourself
  • start the shell to perform the command ("/bin/sh -c")
  • start tar on the folder containing the files to be archived

Edit: For the shell option, your command would look like:

String command = "sh -c \"tar --remove-files -cjvf "+archivedFile+" marketData*\"";

(mind the \"s that delimit the command to be executed by the shell, don't use single quotes ot the shell won't interpret the glob.)

rsp
Thanks rsp.But the folder contains many other types of files and I need to archive only the files starting with marketData. Also the files are dumped by FTP in that folder and the number of files varies. So it seems difficult to use 1st or 3rd method specified by you. I will try with the 2nd one. Can you please elaborate a bit more on it.Thanks,
Amit
It worked Thanks
Amit
A: 

If really you want to create a bzip2 archive, I'd use a Java implementation instead of a native command which is good for portability, for example the one available at http://www.kohsuke.org/bzip2/ (it is not really optimized though, compression seems to be slower than with Java LZMA).

Pascal Thivent