user618111
user618111

Reputation: 439

How to zip only .txt file in a folder using java?

here i'm trying to zip only .txt file in a folder using java.

My code here was found with google and works perfectly but only for a specified .txt file.

Thank you.

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


public class ZipFile
  {
public static void main(String[] args) {

    ZipOutputStream out = null;
    InputStream in = null;
    try {
        File inputFile1 = new File("c:\\Target\\target.txt");// here i want to say only the directroy where .txt files are stored
        File outputFile = new File("c:\\Target\\Archive_target.zip");//here i want to put zipped file in a different directory

        OutputStream rawOut = new BufferedOutputStream(new FileOutputStream(outputFile));
        out = new ZipOutputStream(rawOut);

        InputStream rawIn = new FileInputStream(inputFile1);
        in = new BufferedInputStream(rawIn);


        ZipEntry entry = new ZipEntry("c:\\Target\\target.txt");
        out.putNextEntry(entry);
        byte[] buf = new byte[2048];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    }
    catch(IOException e) {
        e.printStackTrace();
    }
    finally {
        try {
            if(in != null) {
                in.close();
            }
            if(out != null) {
                out.close();
            }
        }
        catch(IOException ignored)
                { }
    }
    }
}

Upvotes: 0

Views: 2452

Answers (4)

user618111
user618111

Reputation: 439

I just add these lines just after "File outputFile = new File("c:\Target\Archive_target.zip"); from my previous code.

code added:

File Dir = new File("c:/Target");
            FilenameFilter filter = new FilenameFilter() {
      public boolean accept(File dir, String name) {
        return !name.startsWith(".txt");
      }
    };
    String[] children = Dir.list(filter);

Upvotes: 1

Yossale
Yossale

Reputation: 14361

Create a FilenameFilter that accepts only *.txt file , and then just use

list = File.list(yourNameFilter);

and then just add all the files in the list to the zip file

Upvotes: 0

mbatchkarov
mbatchkarov

Reputation: 16049

You can get a list of all text files in your directory by using the following method of the File class: String[] list(FilenameFilter filter) Create a File object that points to your DIRECTORY (I know it sounds illogical, but that's the way it is- you can test if it is a directory using isDirectory()) and then use the FilenameFilter to say, for example, accept this file if its name contain ".txt"

Upvotes: 0

camickr
camickr

Reputation: 324128

You need to use File.list(...) to get a list of all the text files in the folder. Then you create a loop to write each file to the zip file.

Upvotes: 1

Related Questions