How to zip only .txt file in a folder using java? - 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)
{ }
}
}
}

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.

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);

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"

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

Related

Zipping multiple folders and files in one output using java

So iam working on a project where i get to a point when i need to zip multiple folders (4folders to be specific) and one file in one output.zip file using java
So is there anyway for me to do it and by the way putting all the folders and file in one directory and then zipping it doesn't give the same result in other words the folders have to be in root level of the zip file
There are several solutions.
This one for example:
public static void zipDirectory(ZipOutputStream zos, File fileToZip, String parentDirectoryName) throws Exception
{
if (fileToZip == null || !fileToZip.exists())
{
return;
}
String zipEntryName = fileToZip.getName();
if (parentDirectoryName!=null && !parentDirectoryName.isEmpty())
{
zipEntryName = parentDirectoryName + "/" + fileToZip.getName();
}
// If we are dealing with a directory:
if (fileToZip.isDirectory())
{
System.out.println("+" + zipEntryName);
if(parentDirectoryName == null) // if parentDirectory is null, that means it's the first iteration of the recursion, so we do not include the first container folder
{
zipEntryName = "";
}
for (File file : fileToZip.listFiles()) // we iterate over all the folders/files and archive them by keeping the structure too.
{
zipDirectory(zos, file, zipEntryName);
}
} else // If we are dealing with a file, then we zip it directly
{
System.out.println(" " + zipEntryName);
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(fileToZip);
zos.putNextEntry(new ZipEntry(zipEntryName));
int length;
while ((length = fis.read(buffer)) > 0)
{
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
}
then you could use this function like this:
try
{
File directoryToBeZipped = new File("C:\\New\\test");
FileOutputStream fos = new FileOutputStream("C:\\New\\test\\archive.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
zipDirectory(zos, directoryToBeZipped, null);
zos.flush();
fos.flush();
zos.close();
fos.close();
} catch (Exception e)
{
e.printStackTrace();
}
Or you could use the ZeroTurnAround ZIP Library. And do this in one line:
ZipUtil.pack(new File("D:\\sourceFolder\\"), new File("D:\\generatedZipFile.zip"));
Dead easy way (though you'll get warnings about proprietary classes)
final String[] ARGS = { "-cfM", "x.zip", "folder1", "folder2", "folder3", "folder4", "file.txt" };
sun.tools.jar.Main.main(ARGS);
It might be worth getting a similar thing that won't give you warnings

How to use a encoded Docx?(unzip)

HI
so my code works like this, I get a docx and a folder to put the unzip files,
String templateLocation = "//path"; //this is where the document is located
String AUX = "//path"; //this is a aux folder that's get the unzip files
unzip(new File(templateLocation), new File(AUX));
and the method unzip is
private static void unzip(File zipfile, File directory) throws IOException {
ZipFile zfile = new ZipFile(zipfile);
Enumeration<? extends ZipEntry> entries = zfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File file = new File(directory, entry.getName());
if (entry.isDirectory()) {
file.mkdirs();
}
else {
file.getParentFile().mkdirs();
InputStream in = zfile.getInputStream(entry);
try {
copy(in, file);
}
finally {
in.close();
}
}
}
}
the thing is that i need to use a external docx that's in Base64
but how?
attempt with this
String wordx = "DocxInBase64";
byte[] dataFileWord = java.util.Base64.getDecoder().decode(wordx);
String dataw = new String(dataFileWord,StandardCharsets.UTF_8);
But im getting something that looks like corrupted
PK����Xs���g����l}'_B�R;�q�u#��.�����~�Hwx�=��4��������pv�{3o�'M,���b���wi�O���0��E]}`�x��?...
any ideas to start with?
Thanks in advance
You can use Apache POI to parse word files.
http://poi.apache.org/document/index.html

Zip files inside without including main folder In android java

im using this code it perfectly create zip files for example i have folder
sdcard/music and when i create xxx.zip file it creates .zip file includes music/songs and also some sub folders in it
but i want to exclude "music" the main Folder in the .zip file and want it to start directly including all songs and subfolders in it,how to do it
i use this way but it takes main folder name as well when zipping
public void unzipbutton(View v){ // button click
try {
FileOutputStream fos = new FileOutputStream("/mnt/sdcard/songs.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
addDirToZipArchive(zos, new File("/mnt/sdcard/music"), null);
zos.flush();
fos.flush();
zos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parrentDirectoryName) throws Exception {
if (fileToZip == null || !fileToZip.exists()) {
return;
}
String zipEntryName = fileToZip.getName();
if (parrentDirectoryName!=null && !parrentDirectoryName.isEmpty()) {
zipEntryName = parrentDirectoryName + "/" + fileToZip.getName();
}
if (fileToZip.isDirectory()) {
System.out.println("+" + zipEntryName);
for (File file : fileToZip.listFiles()) {
addDirToZipArchive(zos, file, zipEntryName);
}
} else {
System.out.println(" " + zipEntryName);
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(fileToZip);
zos.putNextEntry(new ZipEntry(zipEntryName));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
}
anybody help on this,thanks
this has been so tricky till now no way works at the moments for me :/
In your ZipEntry check the full path of zipEntryName, it must be something like: "music/Pink/try.mp3" just invoke a substring in order to obtain as zipEntryName "Pink/try.mp3", your zip file will be the same "songs.zip" but inside of it you'll find the folder "Pink" instead the main folder "music/Pink..."
It worked for me.

Java ZipEntry and Zipoutputstream directory

I have this little piece of code
public void doBuild() throws IOException {
ZipEntry sourceEntry=new ZipEntry(sourcePath);
ZipEntry assetEntry=new ZipEntry(assetPath);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream("output/"+workOn.getName().replaceAll(".bld"," ")+buildNR+".zip"));
out.putNextEntry(sourceEntry);
out.putNextEntry(assetEntry);
out.close();
System.err.println("Build success!");
increaseBuild();
}
So, if I run it it runs trough it fine, creates the .zip and all, but the zip file is empty. sourceEntry and assetEntry are both directories. How could I get those directories to my .zip easily?
For those interested this is a MC mod build system and can be found at https://bitbucket.org/makerimages/makerbuild-system NOTE: the code above is not commited or pushed to there yet!!!!!!!!
Try something like this. The parameter useFullFileNames specifies
whether you want to preserve the full names of the paths to the
files which you're about to zip.
So if you have two files
/dir1/dir2/a.txt
and
/dir1/b.txt
the useFullFileNames specifies if you want to finally see in
the zip file those original paths to the two files or just
the two files with no paths like this
a.txt
and
b.txt
in the root of the zip file which you create.
Note that in my example, the files which are zipped
are actually read and then written to out.
I think you're missing that part.
public static boolean createZip(String fNameZip, boolean useFullFileNames, String... fNames) throws Exception {
try {
int cntBufferSize = 256 * 1024;
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(fNameZip);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte bBuffer[] = new byte[cntBufferSize];
File ftmp = null;
for (int i = 0; i < fNames.length; i++) {
if (fNames[i] != null) {
FileInputStream fi = new FileInputStream(fNames[i]);
origin = new BufferedInputStream(fi, cntBufferSize);
ftmp = new File(fNames[i]);
ZipEntry entry = new ZipEntry(useFullFileNames ? fNames[i] : ftmp.getName());
out.putNextEntry(entry);
int count;
while ((count = origin.read(bBuffer, 0, cntBufferSize)) != -1) {
out.write(bBuffer, 0, count);
}
origin.close();
}
}
out.close();
return true;
} catch (Exception e) {
return false;
}
}

How to change file extension at runtime in Java

I am trying to implement program to zip and unzip a file. All I want to do is to zip a file (fileName.fileExtension) with name as fileName.zip and on unzipping change it again to fileName.fileExtension.
This is how I used to rename files or change its extension.
public static void modify(File file)
{
int index = file.getName().lastIndexOf(".");
//print filename
//System.out.println(file.getName().substring(0, index));
//print extension
//System.out.println(file.getName().substring(index));
String ext = file.getName().substring(index);
//use file.renameTo() to rename the file
file.renameTo(new File("Newname"+ext));
}
edit: John's method renames the file (keeping the extension). To change the extension do:
public static File changeExtension(File f, String newExtension) {
int i = f.getName().lastIndexOf('.');
String name = f.getName().substring(0,i);
return new File(f.getParent(), name + newExtension);
}
This changes only the last extension to a filename, i.e. the .gz part of archive.tar.gz. Therefore it works fine with Linux hidden files, for which the name starts with a .
This is quite safe because if getParent() returns null (i.e. in the event of the parent being the system root) it is "cast" to an empty String as the whole argument to the File constructor is evaluated first.
The only case where you will get a funny output is if you pass in a File representing the system root itself, in which case the null is prepended to the rest of the path string.
Try with:
File file = new File("fileName.zip"); // handler to your ZIP file
File file2 = new File("fileName.fileExtension"); // destination dir of your file
boolean success = file.renameTo(file2);
if (success) {
// File has been renamed
}
I would check, if the file has an extension before changing. The solution below works also with files without extension or multiple extensions
public File changeExtension(File file, String extension) {
String filename = file.getName();
if (filename.contains(".")) {
filename = filename.substring(0, filename.lastIndexOf('.'));
}
filename += "." + extension;
file.renameTo(new File(file.getParentFile(), filename));
return file;
}
#Test
public void test() {
assertThat(changeExtension(new File("C:/a/aaa.bbb.ccc"), "txt"),
is(new File("C:/a/aaa.bbb.txt")));
assertThat(changeExtension(new File("C:/a/test"), "txt"),
is(new File("C:/a/test.txt")));
}
By the same logic as mentioned #hsz, but instead simply use replacement:
File file = new File("fileName.fileExtension"); // creating object of File
String str = file.getPath().replace(".fileExtension", ".zip"); // replacing extension to another
file.renameTo(new File(str));
I want to avoid the new extension just happening to be in the path or filename itself. I like a combination of java.nio and apache StringFilenameUtils.
public void changeExtension(Path file, String extension) throws IOException {
String newFilename = FilenameUtils.removeExtension(file.toString()) + EXTENSION_SEPARATOR_STR + extension;
Files.move(file, Paths.get(newFilename, StandardCopyOption.REPLACE_EXISTING));
}
If you are using Kotlin you can use from this property of your file object:
file.nameWithoutExtension + "extension"
FilenameUtils.getFullPathNoEndSeparator(doc.getDocLoc()) + "/" +
FilenameUtils.getBaseName(doc.getDocLoc()) + ".xml"
My firend was working on a zipper in Java some 4 months back, I got this code from him.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFiles {
List<String> filesListInDir = new ArrayList<String>();
public static void main(String[] args) {
File file = new File("/Users/pankaj/sitemap.xml");
String zipFileName = "/Users/pankaj/sitemap.zip";
File dir = new File("/Users/pankaj/tmp");
String zipDirName = "/Users/pankaj/tmp.zip";
zipSingleFile(file, zipFileName);
ZipFiles zipFiles = new ZipFiles();
zipFiles.zipDirectory(dir, zipDirName);
}
/**
* This method zips the directory
* #param dir
* #param zipDirName
*/
private void zipDirectory(File dir, String zipDirName) {
try {
populateFilesList(dir);
//now zip files one by one
//create ZipOutputStream to write to the zip file
FileOutputStream fos = new FileOutputStream(zipDirName);
ZipOutputStream zos = new ZipOutputStream(fos);
for(String filePath : filesListInDir){
System.out.println("Zipping "+filePath);
//for ZipEntry we need to keep only relative file path, so we used substring on absolute path
ZipEntry ze = new ZipEntry(filePath.substring(dir.getAbsolutePath().length()+1, filePath.length()));
zos.putNextEntry(ze);
//read the file and write to ZipOutputStream
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
fis.close();
}
zos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method populates all the files in a directory to a List
* #param dir
* #throws IOException
*/
private void populateFilesList(File dir) throws IOException {
File[] files = dir.listFiles();
for(File file : files){
if(file.isFile())
filesListInDir.add(file.getAbsolutePath());
else
populateFilesList(file);
}
}
/**
* This method compresses the single file to zip format
* #param file
* #param zipFileName
*/
private static void zipSingleFile(File file, String zipFileName) {
try {
//create ZipOutputStream to write to the zip file
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
//add a new Zip Entry to the ZipOutputStream
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
//read the file and write to ZipOutputStream
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
//Close the zip entry to write to zip file
zos.closeEntry();
//Close resources
zos.close();
fis.close();
fos.close();
System.out.println(file.getCanonicalPath()+" is zipped to "+zipFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I haven't tried it personally, but he and also some of my other friends told me that it works.

Categories