Showing posts with label io. Show all posts
Showing posts with label io. Show all posts

Friday, 23 August 2013

java program to compress files in zip format

// siddhu vydyabhushana // 10 comments
Java comes with “java.util.zip” library to perform data compression in ZIp format. The overall concept is quite straightforward.
  1. Read file with “FileInputStream
  2. Add the file name to “ZipEntry” and output it to “ZipOutputStream

1. Simple ZIP example

Read a file “C:\\spy.log” and compress it into a zip file – “C:\\MyFile.zip“.
package com.mkyong.zip;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
public class App 
{	
    public static void main( String[] args )
    {
    	byte[] buffer = new byte[1024];
 
    	try{
 
    		FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
    		ZipOutputStream zos = new ZipOutputStream(fos);
    		ZipEntry ze= new ZipEntry("spy.log");
    		zos.putNextEntry(ze);
    		FileInputStream in = new FileInputStream("C:\\spy.log");
 
    		int len;
    		while ((len = in.read(buffer)) > 0) {
    			zos.write(buffer, 0, len);
    		}
 
    		in.close();
    		zos.closeEntry();
 
    		//remember close it
    		zos.close();
 
    		System.out.println("Done");
 
    	}catch(IOException ex){
    	   ex.printStackTrace();
    	}
    }
}

2. Advance ZIP example – Recursively

Read all files from folder “C:\\testzip” and compress it into a zip file – “C:\\MyFile.zip“. It will recursively zip a directory as well.
package com.mkyong.zip;
 
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 AppZip
{
    List<String> fileList;
    private static final String OUTPUT_ZIP_FILE = "C:\\MyFile.zip";
    private static final String SOURCE_FOLDER = "C:\\testzip";
 
    AppZip(){
	fileList = new ArrayList<String>();
    }
 
    public static void main( String[] args )
    {
    	AppZip appZip = new AppZip();
    	appZip.generateFileList(new File(SOURCE_FOLDER));
    	appZip.zipIt(OUTPUT_ZIP_FILE);
    }
 
    /**
     * Zip it
     * @param zipFile output ZIP file location
     */
    public void zipIt(String zipFile){
 
     byte[] buffer = new byte[1024];
 
     try{
 
    	FileOutputStream fos = new FileOutputStream(zipFile);
    	ZipOutputStream zos = new ZipOutputStream(fos);
 
    	System.out.println("Output to Zip : " + zipFile);
 
    	for(String file : this.fileList){
 
    		System.out.println("File Added : " + file);
    		ZipEntry ze= new ZipEntry(file);
        	zos.putNextEntry(ze);
 
        	FileInputStream in = 
                       new FileInputStream(SOURCE_FOLDER + File.separator + file);
 
        	int len;
        	while ((len = in.read(buffer)) > 0) {
        		zos.write(buffer, 0, len);
        	}
 
        	in.close();
    	}
 
    	zos.closeEntry();
    	//remember close it
    	zos.close();
 
    	System.out.println("Done");
    }catch(IOException ex){
       ex.printStackTrace();   
    }
   }
 
    /**
     * Traverse a directory and get all files,
     * and add the file into fileList  
     * @param node file or directory
     */
    public void generateFileList(File node){
 
    	//add file only
	if(node.isFile()){
		fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
	}
 
	if(node.isDirectory()){
		String[] subNote = node.list();
		for(String filename : subNote){
			generateFileList(new File(node, filename));
		}
	}
 
    }
 
    /**
     * Format the file path for zip
     * @param file file path
     * @return Formatted file path
     */
    private String generateZipEntry(String file){
    	return file.substring(SOURCE_FOLDER.length()+1, file.length());
    }
}
Output
Output to Zip : C:\MyFile.zip
File Added : pdf\Java-Interview.pdf
File Added : spy\log\spy.log
File Added : utf-encoded.txt
File Added : utf.txt
Done
Read More

Java program to the current working directory

// siddhu vydyabhushana // 5 comments
Here’s an example to check if a directory is empty.

Example

package com.mkyong.file;
 
import java.io.File;
 
public class CheckEmptyDirectoryExample
{
    public static void main(String[] args)
    {	
 
	File file = new File("C:\\folder");
 
	if(file.isDirectory()){
 
		if(file.list().length>0){
 
			System.out.println("Directory is not empty!");
 
		}else{
 
			System.out.println("Directory is empty!");
 
		}
 
	}else{
 
		System.out.println("This is not a directory");
 
	}
    }
}
Read More

Java program to check the directory is empty or not

// siddhu vydyabhushana // 5 comments
Here’s an example to check if a directory is empty.

Example

package com.mkyong.file;
 
import java.io.File;
 
public class CheckEmptyDirectoryExample
{
    public static void main(String[] args)
    {	
 
	File file = new File("C:\\folder");
 
	if(file.isDirectory()){
 
		if(file.list().length>0){
 
			System.out.println("Directory is not empty!");
 
		}else{
 
			System.out.println("Directory is empty!");
 
		}
 
	}else{
 
		System.out.println("This is not a directory");
 
	}
    }
}
Read More

How to copy directory in java

// siddhu vydyabhushana // 8 comments
Here’s an example to copy a directory and all its sub-directories and files to a new destination directory. The code is full of comments and self-explanatory, left me comment if you need more explanation.

Example

Copy folder “c:\\mkyong” and its sub-directories and files to another new folder “c:\\mkyong-new“.
package com.mkyong.file;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
public class CopyDirectoryExample
{
    public static void main(String[] args)
    {	
    	File srcFolder = new File("c:\\mkyong");
    	File destFolder = new File("c:\\mkyong-new");
 
    	//make sure source exists
    	if(!srcFolder.exists()){
 
           System.out.println("Directory does not exist.");
           //just exit
           System.exit(0);
 
        }else{
 
           try{
        	copyFolder(srcFolder,destFolder);
           }catch(IOException e){
        	e.printStackTrace();
        	//error, just exit
                System.exit(0);
           }
        }
 
    	System.out.println("Done");
    }
 
    public static void copyFolder(File src, File dest)
    	throws IOException{
 
    	if(src.isDirectory()){
 
    		//if directory not exists, create it
    		if(!dest.exists()){
    		   dest.mkdir();
    		   System.out.println("Directory copied from " 
                              + src + "  to " + dest);
    		}
 
    		//list all the directory contents
    		String files[] = src.list();
 
    		for (String file : files) {
    		   //construct the src and dest file structure
    		   File srcFile = new File(src, file);
    		   File destFile = new File(dest, file);
    		   //recursive copy
    		   copyFolder(srcFile,destFile);
    		}
 
    	}else{
    		//if file, then copy it
    		//Use bytes stream to support all file types
    		InputStream in = new FileInputStream(src);
    	        OutputStream out = new FileOutputStream(dest); 
 
    	        byte[] buffer = new byte[1024];
 
    	        int length;
    	        //copy the file content in bytes 
    	        while ((length = in.read(buffer)) > 0){
    	    	   out.write(buffer, 0, length);
    	        }
 
    	        in.close();
    	        out.close();
    	        System.out.println("File copied from " + src + " to " + dest);
    	}
    }
}

Result
Directory copied from c:\mkyong  to c:\mkyong-new
File copied from c:\mkyong\404.php to c:\mkyong-new\404.php
File copied from c:\mkyong\footer.php to c:\mkyong-new\footer.php
File copied from c:\mkyong\js\superfish.css to c:\mkyong-new\js\superfish.css
File copied from c:\mkyong\js\superfish.js to c:\mkyong-new\js\superfish.js
File copied from c:\mkyong\js\supersubs.js to c:\mkyong-new\js\supersubs.js
Directory copied from c:\mkyong\images  to c:\mkyong-new\images
File copied from c:\mkyong\page.php to c:\mkyong-new\page.php
Directory copied from c:\mkyong\psd  to c:\mkyong-new\psd
...
Done
Read More

How to delete directory in java

// siddhu vydyabhushana // Leave a Comment
To delete a directory, you can simply use the File.delete(), but the directory must be empty in order to delete it.
Often times, you may require to perform recursive delete in a directory, which means all it’s sub-directories and files should be delete as well, see below example :

Directory recursive delete example

Delete the directory named “C:\\mkyong-new“, and all it’s sub-directories and files as well. The code is self-explanatory and well documented, it should be easy to understand.
package com.mkyong.file;
 
import java.io.File;
import java.io.IOException;
 
public class DeleteDirectoryExample
{
    private static final String SRC_FOLDER = "C:\\mkyong-new";
 
    public static void main(String[] args)
    {	
 
    	File directory = new File(SRC_FOLDER);
 
    	//make sure directory exists
    	if(!directory.exists()){
 
           System.out.println("Directory does not exist.");
           System.exit(0);
 
        }else{
 
           try{
 
               delete(directory);
 
           }catch(IOException e){
               e.printStackTrace();
               System.exit(0);
           }
        }
 
    	System.out.println("Done");
    }
 
    public static void delete(File file)
    	throws IOException{
 
    	if(file.isDirectory()){
 
    		//directory is empty, then delete it
    		if(file.list().length==0){
 
    		   file.delete();
    		   System.out.println("Directory is deleted : " 
                                                 + file.getAbsolutePath());
 
    		}else{
 
    		   //list all the directory contents
        	   String files[] = file.list();
 
        	   for (String temp : files) {
        	      //construct the file structure
        	      File fileDelete = new File(file, temp);
 
        	      //recursive delete
        	     delete(fileDelete);
        	   }
 
        	   //check the directory again, if empty then delete it
        	   if(file.list().length==0){
           	     file.delete();
        	     System.out.println("Directory is deleted : " 
                                                  + file.getAbsolutePath());
        	   }
    		}
 
    	}else{
    		//if file, then delete it
    		file.delete();
    		System.out.println("File is deleted : " + file.getAbsolutePath());
    	}
    }
}

Result

File is deleted : C:\mkyong-new\404.php
File is deleted : C:\mkyong-new\archive.php
...
Directory is deleted : C:\mkyong-new\includes
File is deleted : C:\mkyong-new\index.php
File is deleted : C:\mkyong-new\index.php.hacked
File is deleted : C:\mkyong-new\js\hoverIntent.js
File is deleted : C:\mkyong-new\js\jquery-1.4.2.min.js
File is deleted : C:\mkyong-new\js\jquery.bgiframe.min.js
Directory is deleted : C:\mkyong-new\js\superfish-1.4.8\css
Directory is deleted : C:\mkyong-new\js\superfish-1.4.8\images
Directory is deleted : C:\mkyong-new\js\superfish-1.4.8
File is deleted : C:\mkyong-new\js\superfish-navbar.css
...
Directory is deleted : C:\mkyong-new
Done
Read More

How to create directory in java

// siddhu vydyabhushana // 7 comments
To create a directory in Java, uses the following code :
1. Create a single directory.
new File("C:\\Directory1").mkdir();
2. Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Both methods are returning a boolean value to indicate the operation status : true if succeed, false otherwise.

Example

A classic Java directory example, check if directory exists, if no, then create it.
package com.mkyong.file;
 
import java.io.File;
 
public class CreateDirectoryExample
{
    public static void main(String[] args)
    {	
	File file = new File("C:\\Directory1");
	if (!file.exists()) {
		if (file.mkdir()) {
			System.out.println("Directory is created!");
		} else {
			System.out.println("Failed to create directory!");
		}
	}
 
	File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2");
	if (files.exists()) {
		if (files.mkdirs()) {
			System.out.println("Multiple directories are created!");
		} else {
			System.out.println("Failed to create multiple directories!");
		}
	}
 
    }
}
Read More