Friday, August 7, 2015

Creation of zip file using Java

I want to show how we can create a Zip file in this post.

I am going to use a classes called ZipEntry and ZipOutputStream which are part of java.util.zip.

ZipEntry is used to create a zip file and ZipOutputStream takes data in an output stream and encloses the files in a zip.

I am reading the data from File Input Stream and writing to Zip Output Stream.

Reading count from file input stream and creating a byte of same size to accommodate the byte with file data and write to zip output stream.

I am writing data to File Output Stream and passing the File Output Stream instance variable as parameter to Zip Output Stream for the zip file to be created.

After writing data to zip file, we have to close the zip output stream and file output stream.

Check the below code for creating zip files using Java.


 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.util.zip.ZipEntry;  
 import java.util.zip.ZipOutputStream;  
 public class TestClass {  
      /**  
       * @param args  
       * @throws IOException  
       */  
      public static void main(String[] args) throws IOException {  
           String textFileName = "F:/abc.txt";  
           String zipFileName = "F:/createdFile.zip";  
           File textFile = new File(textFileName);  
           File zipFile = new File(zipFileName);  
           FileInputStream fiStream = new FileInputStream(textFile);  
           FileOutputStream foStream = new FileOutputStream(zipFile);  
           int count = fiStream.read();  
           byte[] bytes = new byte[count];  
           ZipEntry zipEntry = new ZipEntry(textFileName);  
           if (!zipFile.exists()) {  
                zipFile.createNewFile();  
           }  
           ZipOutputStream zoStream = new ZipOutputStream(foStream);  
           zos.putNextEntry(zipEntry);  
           while ((count = fis.read(bytes)) >= 0) {  
                zoStream.write(bytes, 0, count);  
           }  
           fiStream.close();  
           zoStream.closeEntry();  
           zoStream.close();  
           foStream.close();  
      }  
 }  

Sunday, July 5, 2015

Creation of Dynamic HTML using Javascript

I am going to concentrate on creation of dynamic HTML based on javascript in this post. Here I took a simple input tag and submit button in a form and the objective here is like, let's say when a user enters a number in input text box and clicks submit button, I am going to replace the whole page with a select tag that contains the number of drop down elements as the number entered in the input text box.

Try it for yourself, enter a number in the text field and click the submit button with name "Click".



Here is the code that I used:
 <html>  
 <head>  
 <script>  
 function function1() {  
      var a = parseInt(document.getElementById("id1").value);  
      var b = "<select>";  
      for(var c = 0;c<a;c++) {  
           b=b+"<option value=element"+c+">Element "+(parseInt(c)+1)+"</option>";  
      }  
      b=b+"</select>";  
      document.getElementById("id2").innerHTML=b;  
      return false;  
 }  
 </script>  
 </head>  
 <body>  
 <form>  
 <label id="id2"><input id="id1" type="text" />  
 <input onclick="return function1();" type="submit" value="Click" />  
 <label>  
 </label></label></form>  
 </body>  
 </html>  

Sunday, August 3, 2014

Program for creation of XML document using DOM4J

DOM4J is an open-source java library for programming XML in java. 

I used Eclipse as the IDE and Java SE 7 Update 25 for developing the program. 

One have to download the DOM4J jars to start with. It can be downloaded from here DOM4J archive Download link. 

Once downloaded Unrar the rar file and consolidate all the jars from the folders and browse them into the build path of the Eclipse that you're using. Click ALT+ENTER on the project and properties window will open up, navigate to the Java Build Path section, in the Libraries tab click the button Add external jars and browse all the consolidated jars.


 The Eclipse project can be a simple java project.

DOM4J Program:
You can use this program to create the xml document using DOM4J. 

 package com.dom4j.xml;  
 import java.io.BufferedWriter;  
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.io.FileWriter;  
 import java.io.IOException;  
 import java.io.StringReader;  
 import java.io.StringWriter;  
 import javax.xml.transform.OutputKeys;  
 import javax.xml.transform.Source;  
 import javax.xml.transform.Transformer;  
 import javax.xml.transform.TransformerConfigurationException;  
 import javax.xml.transform.TransformerException;  
 import javax.xml.transform.TransformerFactory;  
 import javax.xml.transform.stream.StreamResult;  
 import javax.xml.transform.stream.StreamSource;  
 import org.dom4j.Document;  
 import org.dom4j.DocumentHelper;  
 import org.dom4j.Element;  
 public class XMLCreation {  
      /**  
       * This method creates XML document upon calling.  
       */  
      private void createXML() {  
           Document document = DocumentHelper.createDocument();  
           Element root = document.addElement("Root");  
           Element child1 = root.addElement("Child1")  
                     .addAttribute("attr1", "attr1val")  
                     .addAttribute("loopNode", "no");  
           Element child2 = child1.addElement("Child2").addAttribute("loopNode",  
                     "no");  
           {  
                for (int i = 0; i < 3; i++) {  
                     Element loopNode = child2.addElement("Loop" + i);  
                     loopNode.addAttribute("loopNode", "yes");  
                     loopNode.addText("Loop Child " + i);  
                }  
           }  
           Source source = new StreamSource(new StringReader(document.asXML()));  
           StringWriter stringWriter = new StringWriter();  
           StreamResult streamResult = new StreamResult(stringWriter);  
           File file = null;  
           BufferedWriter bufferedWriter = null;  
           try {  
                file = new File("C:/DemoXMLFile1.xml");  
                file.createNewFile();  
                TransformerFactory transformerFactory = TransformerFactory  
                          .newInstance();  
                Transformer transformer = transformerFactory.newTransformer();  
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
                transformer.setOutputProperty(  
                          "{http://xml.apache.org/xslt}indent-amount", "9");  
                transformer.transform(source, streamResult);  
                bufferedWriter = new BufferedWriter(new FileWriter(  
                          file.getAbsoluteFile()));  
                bufferedWriter.write(streamResult.getWriter().toString());  
                bufferedWriter.flush();  
                bufferedWriter.close();  
           } catch (FileNotFoundException f) {  
                f.printStackTrace();  
           } catch (TransformerConfigurationException t) {  
                t.printStackTrace();  
           } catch (IOException i) {  
                i.printStackTrace();  
           } catch (TransformerException t) {  
                t.printStackTrace();  
           }  
      }  
      /**  
       * Main method  
       *   
       * @param args  
       */  
      public static void main(String args[]) {  
           new XMLCreation().createXML();  
      }  
 }  

1. The process is pretty straight forward. I used Document interface and created an instance to it. 
2. I used this instance to create a root element using Element interface. I added attributes to the node. 
3. Further I created another Element instance and added node as child to the above root element and attributes.
4. I created a loop and every time loop iterates it creates child node to the sub child node and adds text to the loop node. 
5. I made use of TransformerFactory and Transformer to format the xml document. 
6. The normal BufferedWriter to write the xml to the document. 
7. The interface Source stores the document xml details in StringReader, the StringReader creates characterstream. 
8. I created an object to StringWriter class and passed the instance to the StreamResult interface. 
9. The StringWriter converts character stream to the buffered stream. 
10. To the transformer we have included output properties to provide indent to the xml file using setOutputProperty.

One can also use the Scanner class to provide file paths and file names as dynamic parameters.

The output file I got with Indent 9:



Suggestions are welcome. Please feel free to comment.

Comments

blog comments powered by Disqus