By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,160 Members | 1,983 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,160 IT Pros & Developers. It's quick & easy.

Zip files in other directories

P: n/a
Trying to figure out how to use the following program to zip up files
in another directory other than current "." Using current works fine,
I substitute it with a path "c:\\stuff" I get the following run-time
error:

Adding: file1.txt

java.io.FileNotFoundException: file1.txt (The system cannot find the
file specified)

at java.io.FileInputStream.open(Native Method)

at java.io.FileInputStream.<init>(FileInputStream.jav a:103)

at java.io.FileInputStream.<init>(FileInputStream.jav a:66)

at Zip.main(Zip.java:25)
It finds the first file but then fails. Here is the code:

import java.util.*;
import java.io.*;
import java.util.zip.*;

public class Zip {
static int BUFFER = 4096;
static String dir = "c:\\stuff";
public static void main (String argv[]) {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new
FileOutputStream("c:\\blah.zip");
ZipOutputStream out = new ZipOutputStream(new
BufferedOutputStream(dest));
//out.setMethod(ZipOutputStream.STORED);

// get a list of files from current directory
File f = new File(dir);
String[] files = f.list();
byte data[] = new byte[BUFFER];

for (int i=0; i < files.length; i++) {

System.out.println("Adding: "+files[i]);
FileInputStream fi = new
FileInputStream(files[i]);
origin = new
BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(files[i]);
out.putNextEntry(entry);
int count;
while((count = fi.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}

I am a Windows (XP) platform. Thanks for the help.
Jul 17 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
or**********@yahoo.com (Alex) wrote in message news:<11**************************@posting.google. com>...
Trying to figure out how to use the following program to zip up files
in another directory other than current "." Using current works fine,
I substitute it with a path "c:\\stuff" I get the following run-time
error:


[snipped...]

IIRC the File.list() method returns an array of file and directory
names only, not including their path. When you were using them
to add to your zip file, the unqualified names would have therefore
defaulted to the current working directory.

To fix the problem, either pre-pend the path to each name ...or...
better still, use the File.listFiles() method to return an array
of File objects, instead of an array of String's. You can then
get the full name of the file from that object.

-FISH- ><>
Jul 17 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.