Tuesday, November 20, 2012

Java class to Write Data into a Text File


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.Writer;
import java.io.FileNotFoundException;
import java.io.IOException;

public class WriteTextFileExample {
    public static void main(String[] args) {
        Writer writer = null;

        try {
            String text = "This is a text file";

            File file = new File("write.txt");
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(text);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Read Data From Excel and Write it into Text file



import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 
public class ReadExcel {
 
    public static void main( String [] args ) {
    Writer writer = null;
        try {
   
             InputStream input = new BufferedInputStream(
                        new FileInputStream("C:/MyWorkSpace/Temp/poi-test.xls"));
            POIFSFileSystem fs = new POIFSFileSystem( input );
            HSSFWorkbook wb = new HSSFWorkbook(fs);
            HSSFSheet sheet = wb.getSheetAt(0); //sheet of excel
         
            File file = new File("writedatasamp.txt");  
            writer = new BufferedWriter(new FileWriter(file));
            Iterator rows = sheet.rowIterator();
            while( rows.hasNext() ) {  
                HSSFRow row = (HSSFRow) rows.next();
                System.out.println("\n");
                Iterator cells = row.cellIterator();
               
                writer.write("insert into Emp values(");
                while( cells.hasNext() ) {
                     
                    HSSFCell cell = (HSSFCell) cells.next();
                    if(HSSFCell.CELL_TYPE_NUMERIC==cell.getCellType()) {
                    System.out.print( cell.getNumericCellValue()+"     "+cell.getColumnIndex() );
                    if(cell.getColumnIndex()==3)
                  writer.write(String.valueOf(cell.getNumericCellValue()));
                    else
                    writer.write(String.valueOf(cell.getNumericCellValue()+","));
                    }
                    else
                    if(HSSFCell.CELL_TYPE_STRING==cell.getCellType()) {
                        System.out.print( cell.getStringCellValue()+"     " );
                        writer.write("'"+cell.getStringCellValue()+"',");
                    }
                    else
                        if(HSSFCell.CELL_TYPE_BOOLEAN==cell.getCellType()) {
                        System.out.print( cell.getBooleanCellValue()+"     " );
                       writer.write("'"+String.valueOf(cell.getBooleanCellValue()+"',"));
                        }
                        else
                            if(HSSFCell.CELL_TYPE_BLANK==cell.getCellType())
                                System.out.print( "BLANK     " );
                                else
                            System.out.print("Unknown cell type");
             
                   
                }
                 
                writer.write(");"+"\n");
            }
           
             
        } catch ( IOException ex ) {
            ex.printStackTrace();
        } finally {             try {                 if (writer != null) {                     writer.close();                 }             } catch (IOException e) {                 e.printStackTrace();             }         }
    }
     
}


Thursday, November 15, 2012

POI API to Write Data into Excel Sheet


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

public class PoiWriteExcelFile {

public static void main(String[] args) {
try {
FileOutputStream fileOut = new FileOutputStream("poi-test.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
//creating sheets in excel
HSSFSheet worksheet = workbook.createSheet("POI Worksheet1");
HSSFSheet worksheet2 = workbook.createSheet("Worksheet2");

//adding a row to sheet
HSSFRow row1 = worksheet.createRow(0);

HSSFCell cellA1 = row1.createCell(0);
cellA1.setCellValue("Hello");
/*HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellA1.setCellStyle(cellStyle);*/

HSSFCell cellB1 = row1.createCell(1);
cellB1.setCellValue("Goodbye");
/*cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellB1.setCellStyle(cellStyle);*/

HSSFCell cellC1 = row1.createCell(2);
cellC1.setCellValue(true);

HSSFCell cellD1 = row1.createCell(3);
cellD1.setCellValue(new Date());
/*cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat
.getBuiltinFormat("m/d/yy h:mm"));
cellD1.setCellStyle(cellStyle);*/


HSSFRow s2row1 = worksheet2.createRow(0);
HSSFCell s2cellA1 = s2row1.createCell(0);
s2cellA1.setCellValue("Hello");
HSSFCell s2cellA2 = s2row1.createCell(1);
s2cellA2.setCellValue("secondcell");
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}
jars required for this Program are ,



Java Program to Read a File Data Line By Line


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
class ReadFileExample
{
 public static void main(String args[])
  {
  try{
  // Open the file that is the first
  FileInputStream fstream = new FileInputStream("C:/MyWorkSpace/Temp/src/Fileall.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {
  // Print the content on the console
  System.out.println (strLine);
  }
  //Close the input stream
  in.close();
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}

Sunday, November 11, 2012

Java class to execute batch file(*.bat ).


import java.io.IOException;

public class RunBatchFile {

    public static void main(String[] args) {
        String bfile= "D:/sample.bat";
        Runtime runtime = Runtime.getRuntime();
        
        try {
            runtime.exec(bfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        System.out.println("Done");
    }
}

Java class to Generate PDF




import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class PdfGenerate {

public static void main(String[] args) {
try {
OutputStream file = new FileOutputStream(new File("L:\\MySamplePdf.pdf"));

Document document = new Document();
PdfWriter.getInstance(document, file);

document.open();
document.add(new Paragraph("Hello World, iText"));
document.add(new Paragraph(new Date().toString()));
PdfPTable table = new PdfPTable(3); // 3 columns.

           PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
           PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
           PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
           PdfPCell cell4 = new PdfPCell(new Paragraph("Cell 4"));
           PdfPCell cell5 = new PdfPCell(new Paragraph("Cell 5"));
           PdfPCell cell6 = new PdfPCell(new Paragraph("Cell 6"));


           table.addCell(cell1);
           table.addCell(cell2);
           table.addCell(cell3);
           table.addCell(cell4);
           table.addCell(cell5);
           table.addCell(cell6);


           document.add(table);

document.close();
file.close();

} catch (Exception e) {

e.printStackTrace();
}
}
}


Jar File Required are,
itextpdf-5.2.1.jar

Java class to connect to MQ. Post and Retreive messages


package com.kiran.mq;

import java.io.IOException;

import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;

/**
 * Java class to connect to MQ. Post and Retreive messages.
 */
public class MQConnectionTest {

    String qMngrStr = "";
    //String user = "";
    //String password = "";
    String queueName = "";
    String hostName = "";
    int port = 0;
    String channel = "";
    //message to put on MQ.
    String msg = "Hello World, WelCome to MQ.";
    //Create a default local queue.
    MQQueue defaultLocalQueue;
    MQQueueManager qManager;
    
    /**
     * Initialize the MQ
     *
     */
    public void init(){
        
        //Set MQ connection credentials to MQ Envorinment.
         MQEnvironment.hostname = hostName;
         MQEnvironment.channel = channel;
         MQEnvironment.port = port;
         MQEnvironment.userID = user;
         MQEnvironment.password = password;
         //set transport properties.(optional)
         MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
         
         try {
             //initialize MQ manager.
            qManager = new MQQueueManager(qMngrStr);
        } catch (MQException e) {
            e.printStackTrace();
        }
    }
    
    
    public void putAndGetMessage(){
        
        int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT; 
        try {
            defaultLocalQueue = qManager.accessQueue(queueName, openOptions);
            
            MQMessage putMessage = new MQMessage();
            putMessage.writeUTF(msg);
            
            //specify the message options...
            MQPutMessageOptions pmo = new MQPutMessageOptions(); 
            // accept 
            // put the message on the queue
            defaultLocalQueue.put(putMessage, pmo);
            
            System.out.println("Message is put on MQ.");
            
            //get message from MQ.
            MQMessage getMessages = new MQMessage();
            //assign message id to get message.
            getMessages.messageId = putMessage.messageId;
            
            //get message options.
            MQGetMessageOptions gmo = new MQGetMessageOptions();
            defaultLocalQueue.get(getMessages, gmo);
            
            String retreivedMsg = getMessages.readUTF();
            System.out.println("Message got from MQ: "+retreivedMsg);
            
        } catch (MQException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        
        System.out.println("Processing Main...");
        
        MQConnectionTest mqt= new MQConnectionTest();
        
        //initialize MQ.
        mqt.init();
        
        //put and retreive message from MQ.
        mqt.putAndGetMessage();
        
        System.out.println("Okkkkkkkkkkkkkkk...........Done!");
    }
    
}


Jars required for this above Program are,
com.ibm.mq.jar
com.ibm.mq.jms.admin.jar
com.ibm.msg.client.jms.jar
com.ibm.msg.client.jms.internal.jar
com.ibm.ws.sib.client.thin.jms.jar
j2ee.jar,(search all jms amd mq related jars in websphere application server home)