Hi Alhisnawy,
Below is my version of code. Hope it fulfills your need.Create a sourceFile and goahead.
/**
* Program to take an single input file of text and create an zipped(compressed) file which contains the contents of the input file without any white spaces.
* reference:
http://java.sun.com/developer/technicalArticles/Programming/compression/ */
import java.io.*;
import java.util.StringTokenizer;
import java.util.zip.*;
public class ZipFile {
/**
* @variable inputFileName: Input File to be zipped.
* @variable tempInputFile: Temporary file created to hold the contents of the input file without any white spaces.
*/
static final int BUFFER = 2048;
public static void main(String[] args) {
String inputFileName = "sourceFile";
String destination = "C:\\JavaZip\\zippedFile.zip";
ZipFile zipObject = new ZipFile();
try{
BufferedInputStream origin = null;
byte data[] = new byte[BUFFER];
int count;
FileOutputStream fos = new FileOutputStream(destination);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
/** Call truncateWhiteSpaces(String name) on the input file to truncate white spaces and
* get a temporary file which has all the words of the original file without any white spaces */
String tempInputFile = zipObject.truncateWhiteSpaces(inputFileName);
/** Now file to be zipped is ->tempInputFile. */
FileInputStream fis = new FileInputStream(tempInputFile);
origin = new BufferedInputStream(fis,BUFFER);
/** Zip it **/
ZipEntry entry = new ZipEntry(tempInputFile);
zos.putNextEntry(entry);
while((count = origin.read(data, 0, BUFFER))!= -1) {
zos.write(data, 0, count);
}
origin.close();
zos.close();
/** Delete the temporary file created **/
zipObject.deleteFile(tempInputFile);
}catch(Exception e){
System.err.print("Error Occured");
e.printStackTrace();
}
}
/** This method reads the input file and writes a file which has all the words/content of the input file without any white spaces. **/
public String truncateWhiteSpaces(String fileName){
String tempInputFile = "OutputFile";
try{
File file =new File(tempInputFile);
FileWriter fileWriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fileWriter);
PrintWriter out = new PrintWriter(writer);
FileReader fileReader = new FileReader(fileName);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
while((line = reader.readLine()) != null){
StringTokenizer st = new StringTokenizer(line);
while(st.hasMoreTokens()){
String token = st.nextToken();
out.write(token, 0, token.length());
}
}
reader.close();
writer.close();
out.close();
}catch(Exception e){
e.printStackTrace();
}
return tempInputFile;
}
/** This method deletes a file(Used to delete the temporary file). **/
public void deleteFile(String fileName){
File file = new File(fileName);
file.delete();
}
}
Regards,
javaquest2010.