Bharath Kumar Reddy
Bharath Kumar Reddy

Reputation: 53

How to zip only .txt files using java

package codes;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Rough {


public static void main(String[] args) throws IOException {
private static final String FOLDER_PATH = "C:\\Users\\s13w63\\Desktop\\Zip";    

File dir = new File(FOLDER_PATH);

    File[] files = dir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File directory, String fileName) {
            if (fileName.endsWith(".txt")) {
                return true;
            }
            return false;
        }
    });


    for (File f : files)
    {
        FileOutputStream fos=new FileOutputStream("C:\\Users\\s13w63\\Desktop\\Source.zip");
        ZipOutputStream zos=new ZipOutputStream(fos);
        ZipEntry ze=new ZipEntry(f.getCanonicalPath());
        zos.putNextEntry(ze);
        zos.close();
        System.out.println(f.getCanonicalPath());
    }
}
}

I tried this code to ZIP the files, it was showing the file names but not zipping them. Should I have to add anything..and it was showing there is error in code continue to compile??

Help me to solve this issue

Upvotes: 0

Views: 1013

Answers (2)

Balaji Katika
Balaji Katika

Reputation: 3005

Bharat, Please paste the error message that you see

Also, I see few issues with your approach. You might need to do the below things

  • Take out the definition of FOS and ZOS from the for loop and move it above it...
  • The code to add the file is missing...
  • Move zos.close() after the for loop
  • You could use the below code to add contents of the text file to the ZipOutputStream

/**
* Adds a file to the current zip output stream
* 
* @param file
*            the file to be added
* @param zos
*            the current zip output stream
*/
private static void addFileToZip(File file, ZipOutputStream zos) { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { zos.putNextEntry(new ZipEntry(file.getName())); byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0;

         while ((read = bis.read(bytesIn)) != -1) {
             zos.write(bytesIn, 0, read);
         }
         zos.closeEntry();
     } catch (IOException e) {
             //Take appropriate action
     }
 }

Upvotes: 1

fge
fge

Reputation: 121730

Use java.nio.file; it has a very nice solution to your problem.

Illustration:

final Path zipPath = Paths.get("C:\\Users\\s13w63\\Desktop\\Source.zip");

final Path dir = Paths.get("C:\\Users\\s13w63\\Desktop\\Zip");
final DirectoryStream<Path> dirstream
    = Files.newDirectoryStream(dir, "*.txt");

final URI uri = URI.create("jar:" + zipPath.toUri());
final Map<String, ?> env = Collections.emptyMap();

String filename;

try (
    final FileSystem zipfs = FileSystems.newFileSystem(uri, env);
) {
    for (final Path entry: dirstream) {
        filename = dir.relativize(entry).toString();
        Files.copy(entry, zipfs.getPath("/" + filename));
    }
}

Yes, that's right, you can open a zip file as a FileSystem; as such, every operation in Files can be used "on a zip"!

This is JSR 203 for you; you even have FileSystem implementations in memory, over FTP, Dropbox, and others.


Note about the necessity to have the file name as a String: it is because you cannot .resolve() a Path against another if the other Path is from a different provider; I have published a package which solves this particular problem (among others) and has a MorePaths.resolve() method for such cases.

Upvotes: 6

Related Questions