Search This Blog

Sunday, July 11, 2010

Article: Compressing and Decompressing Data Using Java APIs

Decompressing and Extracting Data from a ZIP file


The java.util.zip package provides classes for data compression and decompression. Decompressing a ZIP file is a matter of reading data from an input stream. The java.util.zip package provides a ZipInputStream class for reading ZIP files. A ZipInputStream can be created just like any other input stream. For example, the following segment of code can be used to create an input stream for reading data from a ZIP file format:

FileInputStream fis = new FileInputStream("figs.zip");
ZipInputStream zin = new
ZipInputStream(new BufferedInputStream(fis));

Once a ZIP input stream is opened, you can read the zip entries using the getNextEntry method which returns a ZipEntry object. If the end-of-file is reached, getNextEntry returns null:

ZipEntry entry;
while((entry = zin.getNextEntry()) != null) {
// extract data
// open output streams
}


Now, it is time to set up a decompressed output stream, which can be done as follows:

int BUFFER = 2048;
FileOutputStream fos = new
FileOutputStream(entry.getName());
BufferedOutputStream dest = new
BufferedOutputStream(fos, BUFFER);


Note: In this segment of code we have used the BufferedOutputStream instead of the ZIPOutputStream. The ZIPOutputStream and the GZIPOutputStream use internal buffer sizes of 512. The use of the BufferedOutputStream is only justified when the size of the buffer is much more than 512 (in this example it is set to 2048). While the ZIPOutputStream doesn't allow you to set the buffer size, in the case of the GZIPOutputStream however, you can specify the internal buffer size as a constructor argument.

In this segment of code, a file output stream is created using the entry's name, which can be retrieved using the entry.getName method. Source zipped data is then read and written to the decompressed stream:

while ((count = zin.read(data, 0, BUFFER)) != -1) {
//System.out.write(x);
dest.write(data, 0, count);
}

And finally, close the input and output streams:

dest.flush();
dest.close();
zin.close();

The source program in Code Sample 1 shows how to decompress and extract files from a ZIP archive. To test this sample, compile the class and run it by passing a compressed file in ZIP format:

prompt> java UnZip somefile.zip

Note that somefile.zip could be a ZIP archive created using any ZIP-compatible tool, such as WinZip.

Code Sample 1: UnZip.java

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

public class UnZip {
final int BUFFER = 2048;
public static void main (String argv[]) {
try {
BufferedOutputStream dest = null;
FileInputStream fis = new
FileInputStream(argv[0]);
ZipInputStream zis = new
ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " +entry);
int count;
byte data[] = new byte[BUFFER];
// write the files to the disk
FileOutputStream fos = new
FileOutputStream(entry.getName());
dest = new
BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER))
!= -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
zis.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}


It is important to note that the ZipInputStream class reads ZIP files sequentially. The class ZipFile, however, reads the contents of a ZIP file using a random access file internally so that the entries of the ZIP file do not have to be read sequentially.

Note: Another fundamental difference between ZIPInputStream and ZipFile is in terms of caching. Zip entries are not cached when the file is read using a combination of ZipInputStream and FileInputStream. However, if the file is opened using ZipFile(fileName) then it is cached internally, so if ZipFile(fileName) is called again the file is opened only once. The cached value is used on the second open. If you work on UNIX, it is worth noting that all zip files opened using ZipFile are memory mapped, and therefore the performance of ZipFile is superior to ZipInputStream. If the contents of the same zip file, however, are be to frequently changed and reloaded during program execution, then using ZipInputStream is preferred.

This is how a ZIP file can be decompressed using the ZipFile class:

1. Create a ZipFile object by specifying the ZIP file to be read either as a String filename or as a File object:

ZipFile zipfile = new ZipFile("figs.zip");
2. Use the entries method, returns an Enumeration object, to loop through all the ZipEntry objects of the file:

while(e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
// read contents and save them
}

3. Read the contents of a specific ZipEntry within the ZIP file by passing the ZipEntry to getInputStream, which will return an InputStream object from which you can read the entry's contents:

is = new
BufferedInputStream(zipfile.getInputStream(entry));



4. Retrieve the entry's filename and create an output stream to save it:

byte data[] = new byte[BUFFER];
FileOutputStream fos = new
FileOutputStream(entry.getName());
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}


5. Finally, close all input and output streams:

dest.flush();
dest.close();
is.close();

The complete source program is shown in Code Sample 2. Again, to test this class, compile it and run it by passing a file in a ZIP format as an argument:

prompt> java UnZip2 somefile.zip

Code Sample 2: UnZip2.java

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

public class UnZip2 {
static final int BUFFER = 2048;
public static void main (String argv[]) {
try {
BufferedOutputStream dest = null;
BufferedInputStream is = null;
ZipEntry entry;
ZipFile zipfile = new ZipFile(argv[0]);
Enumeration e = zipfile.entries();
while(e.hasMoreElements()) {
entry = (ZipEntry) e.nextElement();
System.out.println("Extracting: " +entry);
is = new BufferedInputStream
(zipfile.getInputStream(entry));
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos = new
FileOutputStream(entry.getName());
dest = new
BufferedOutputStream(fos, BUFFER);
while ((count = is.read(data, 0, BUFFER))
!= -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
is.close();
}
} catch(Exception e) {
e.printStackTrace();
}
}
}


Compressing and Archiving Data in a ZIP File

The ZipOutputStream can be used to compress data to a ZIP file. The ZipOutputStream writes data to an output stream in a ZIP format. There are a number of steps involved in creating a ZIP file.

1. The first step is to create a ZipOutputStream object, to which we pass the output stream of the file we wish to write to. Here is how you create a ZIP file entitled "myfigs.zip":

FileOutputStream dest = new
FileOutputStream("myfigs.zip");
ZipOutputStream out = new
ZipOutputStream(new BufferedOutputStream(dest));

2. Once the target zip output stream is created, the next step is to open the source data file. In this example, source data files are those files in the current directory. The list command is used to get a list of files in the current directory:

File f = new File(".");
String files[] = f.list();
for (int i=0; i System.out.println("Adding: "+files[i]);
FileInputStream fi = new FileInputStream(files[i]);
// create zip entry
// add entries to ZIP file
}


Note: This code sample is capable of compressing all files in the current directory. It doesn't handle subdirectories. As an exercise, you may want to modify Code Sample 3 to handle subdirectories.


3. Create a zip entry for each file that is read:
4. ZipEntry entry = new ZipEntry(files[i])) Before you can write data to the ZIP output stream, you must first put the zip entry object using the putNextEntry method:
5. out.putNextEntry(entry); Write the data to the ZIP file:

int count;
while((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}

6. Finally, you close the input and output streams:

origin.close();
out.close();

The complete source program is shown in Code Sample 3.

Code Sample 3: Zip.java

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

public class Zip {
static final int BUFFER = 2048;
public static void main (String argv[]) {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new
FileOutputStream("c:\\zip\\myfigs.zip");
ZipOutputStream out = new ZipOutputStream(new
BufferedOutputStream(dest));
//out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER];
// get a list of files from current directory
File f = new File(".");
String files[] = f.list();

for (int i=0; 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 = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}

Saturday, May 8, 2010

GOOGLE APP ENGINE

When the two of us first heard the promise of Google App Engine, we realized that the chance to bring this kind of simplicity to Java developers was too good of an opportunity to pass up. When App Engine launched publicly, we were excited to see that Java language support was both the first and the most popular request filed in the Issue Tracker. We were also thrilled to see that this enthusiasm extended beyond the Java language to all of the various programming languages that have been implemented on top of the Java virtual machine -- not to mention all of the popular web frameworks and libraries.

But we also knew that Java developers are choosy:

* They live by their powerful tools (Eclipse, Intellij, NetBeans, Ant, etc.).
* They try to avoid lock-in and strive for re-use. Standards-based development (defacto or otherwise) is key.
* They harness sophisticated libraries to perform language feats which are nearly magical (GWT, Guice, CGLIB, AspectJ, etc...).
* They even use alternate languages on the JVM, like Groovy, Scala, and JRuby.

We wanted to give developers something that they could be ecstatic about, but we knew we would have to marry the simplicity of Google App Engine with the power and flexibility of the Java platform. We also wanted to leverage the App Engine infrastructure -- and by extension Google's infrastructure -- as much as possible, without giving up compatibility with existing Java standards and tools.

And so that's what we did. App Engine now supports the standards that make Java tooling great. (We're working on the tooling too, with Google Plugin for Eclipse). It provides the current App Engine API's and wraps them with standards where relevant, like the Java Servlet API, JDO and JPA, javax.cache, and javax.mail. It also provides a secure sandbox that's powerful enough to run your code safely on Google's servers, while being flexible enough for you to break abstractions at will.

Sunday, May 2, 2010

Importance of Coffee.....................

A group of alumni, highly established in their careers, got together to visit their old university professor.
Conversation soon turned into complaints about stress in work and life. Offering his guests coffee, the professor went to the kitchen and returned with a large pot of coffee and an assortment of cups porcelain, plastic, glass, crystal, some plain looking, some expensive, some exquisite - telling them to help themselves to hot coffee.

When all the students had a cup of coffee in hand, the professor said: "If you noticed, all the nice looking expensive cups were taken up, leaving behind the plain and cheap ones. While it is but normal for you to want only the best for yourselves, that is the source of your problems and stress. What all of you really wanted was coffee, not the cup, but you consciously went for the best cups and were eyeing each other's cups. Now if life is coffee, then the jobs, money and position in society are the cups. They are just tools to hold and contain Life, but the real quality of Life doesn't change. Sometimes, by concentrating only on the cup, we fail to enjoy the coffee in it."

Don't let the cups drive you... Enjoy the coffee instead.

Sunday, April 25, 2010

Why most ly mens are in Prison............

 
Women - Multiple process
Women's brains designed to
concentrate multiple task at a time .
Women can Watch a TV and Talk over phone and cook the new recipe.

Men - Single Process

Men's brain designed to concentrate only one work at a time. Men can not watch a TV and talk over the phone at the same time. He stops the TV while Talking. He can either watch TV or talk over the  phone or cook.


LANGUAGE.
 
Women can easily learn many languages. Her brain sets up. But can not find the solutions to problems. Men can not easily learn languages; he can easily solve the problems.
3 year old gal has three times higher vocabulary than 3 year old boy.

ANALYTICAL SKILL
 
Men's brain has lot of space for handling the analytical process. So easily he can analyze and find the solution for a process.
He can design (blue print) a map of a building easily.
If a complex map is viewed by women, she can not understand it. She can not understand the details of the map easily.
For her it is dump of lines in a paper.

CAR DRIVING.

While driving a car, men's analytical spaces are used in his brain. He can drive a car fastly. If he see an object at long distance, immediately his brain classifies the object (bus or van or car) direction and speed of the object and driving accordingly. Where as women take a long time to recognize the object direction/ speed. His single process mind stops the audio in the car (if any), then concentrating only on the driving.
You can often watch, while men driving the car fastly, the women sit next to him will shout, "GO SLOW" , "CARE FULL", "AAHHH", "OHH GOD.."
..etc..


LIE
 
Many times, when men lie to women face to face, they get caught easily.
Her super natural brain observes the facial expression 70%, and the body language 20% and the words coming from the mouth 10%. So he is easily caught while lieing.
Men's brain does not have this.
Women easily lie to men face to face.
So guys, While lieing to your girls, use phone, or letter or close all the lights or cover your/her face with blanket.
Don't lie face to face.



PROBLEM.
 
End of day, if men have lot of problems, his brain clearly classifies the problems and puts the problems in individual rooms in the brain and then finds the solution one by one. You can see many guys looking at the sky for a long time. If you disturb him, he gets irritated.
End of Day, if women have lot of problems, her brain can not classify the problems. she wants some one to hear that. After telling everything to a person she goes happily to bed. She does not worry about the problem being solved or not.



WANTS
 
Men want status, success, solutions, big process... etc Women want relationship, friends, family...etc...



UNHAPPY

If women are unhappy with their relations, they can not concentrate on work.
If men unhappy with their work, they can not concentrate on the relations.


MAP

Men can easily locate the place in a complex map. His analytical brain does this. While watching a cricket match in a stadium with full of crowd, men can leave his seat to T shop and keeps everything in his mind and comes back to his seat with out problems. He uses his analytical skills space of brain.
Women can't do this. They often lost their way to their seat.


LIFE

Life is very easy to Men. One good job, one alcohol bottle is enough for them.
Women want everything in life.


SPEECH
 
Women use indirect languages in speech.
Geeta asked Vijay, "vijay do you like to have a cup of coffee?"
This means, Geeta wants a cup of coffee.    
In the morning......."Darling, do you think, it will be good to have an Omllette for breakfast?".


Men use direct language. "Geeta, I want to have a cup of coffee, Pls stop the car when you see a coffee shop".
In the morning...."Darling, Can you please prepare an omllette for breakfast?".


HANDLING EMOTION

Women talk a lot without thinking.

Men act a lot with out thinking.
                         That's why many of prisoners are men all over the world.

 
 

Amazing Pics

https://mail.google.com/mail/?ui=2&ik=e39b5a52f7&view=att&th=12825c72e9d165f1&attid=0.8&disp=emb&realattid=0.10&zw

Saturday, April 24, 2010

NETBEANS NEWS LETTER

Calendar

Are You a Swing Developer In Norway?

Are you in Norway (or thereabouts)? Toni Epple and Geertjan Wielenga will be giving a NetBeans Platform Certified Training and related presentations in Oslo and Bergen in the next two weeks! They look forward to meeting developers (universities, institutions, companies, JUGs) interested in developing Swing applications on the NetBeans Platform. Contact Geertjan to get in touch.

Great Indian Developer Summit 2010

If you attend the Great Indian Developer Summit next week in Bangalore to learn more about rich internet applications, cloud computing and Java, come to our booth (#9) where we demo NetBeans IDE and the new JavaFX Composer. Register now!

NetBeans Platform Certified Training Kraków 2010

Geertjan Wielenga, Toni Epple, and Karol Harezlak meet up with the Polish Java User Group in Kraków next week for another round of NetBeans Platform training. If you are in the area, join us and learn how to develop state-of-the-art Swing Desktop applications!

Articles

DZone: New Cool Tools for OSGi Developers

The upcoming NetBeans IDE 6.9 brings new tools for OSGi developers, specifically for those who want to use Swing as their UI toolkit. The NetBeans Platform 6.9 understands what an OSGi bundle is and you'll be able to import OSGi bundles into your NetBeans Platform applications.

JavaFX Database Programming with Java DB

Who said JDBC programming with Java was difficult? With JavaFX you can build media-rich applications with far less code than you would with Swing, yet you can still call into your existing Java codebase. This includes databases via JDBC as well, but there are some tricks you'll need to know, which we'll explore here.

Tech Tip: Automatic Import Statement Organizer

A student of the NetBeans Platform Certified Training created a new plugin that helps you reorganize import statements. It works in NetBeans IDE 6.7.1 or 6.8.

Training

Complete List of Macro Keywords for the NetBeans Java Editor

In NetBeans IDE's Java editor, you can create macros by clicking the "Start/Stop Macro Recording" button. You can also edit macros in the Options window, in the Editor>Macros tab. A special macro syntax is used to define these macros -- here's the complete list.

Generate a NetBeans Platform Installer with NetBeans IDE 6.9

In the upcoming NetBeans IDE 6.9, you'll be able to use the IDE to generate installers of your NetBeans Platform applications.

Blogs

Tech Tip: Packaging Fun

When using NetBeans to create a JavaFX application, it creates JNLP files, a JavaFX JAR file, and a default HTML page to run in the browser. This is a great way to run standalone or in a browser, but how do you package the app when you want to deploy it to an application server like Glassfish? Matt Warman shares some advice.

Net Beans intership Proposal

Project News

Sign Up to Localize NetBeans 6.9!

Localization of NetBeans 6.9 is about to start! Join the NetBeans Localization Project today to help translate the next NetBeans release into your native language. You can sign up to localize the Platform, specific modules or the entire IDE!

Training

How to Create an OSGi Bundle in NetBeans IDE and Deploy to GlassFish

This tutorial from Arun Gupta shows how to create an OSGi bundle using NetBeans IDE and deploying to GlassFish.

Developing Naked Object Applications in NetBeans IDE

Developer Andrea Maietta shows two ways to create simple Naked Object applications using the NetBeans IDE.

Tech Tip: Add Closing Parenthesis to Java Statement from Keyboard

Stop the guesswork about how many closing parentheses you need with this tech tip from Harris Goldstone.

How to Send Email with Java Mail, CKEditor and NetBeans

This tutorial shows you how to send email using Java Mail 1.4.3, CKEditor and the NetBeans IDE.

Community

Three-Month Internship for NetBeans Platform Developer

No, we're not hiring (sorry!), but MedImmune is. The Maryland-based biotech company is looking for a biophysics, engineering, or computer science graduate student with experience using NetBeans or Java, and knowledge of the NetBeans Platform.

Automatic Import Statement Organizer in NetBeans IDE

Developer Jens Hofschröer's new plugin for the NetBeans IDE lets you reorganize or sort import statements. The module is already collecting fans!

NetBeans 6.8 Plugin for Scala 2.8.0 RC1

A NetBeans 6.8 plugin for Scala 2.8.0 RC1 is now available from NetBeans module developer and Dream Team member Caoyuan Deng.

This issue was brought to you by: Tinuola Awopetu
If you do not want to receive this newsletter, you can unsubscribe here