Thought of the Day!!!!!!!

Don't make EXCUSES, make IMPROVEMENTS. - Tyra Banks

Search This Blog

Saturday, August 19, 2017

How to read data from Excel files (.xls or .xlsx) using JAVA?

Question: How to read data from Excel files (.xls or .xlsx) using JAVA?

Code: 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelHandling
{

public static void main(String[] args) throws IOException
{
String filePath="input_Excel//testData.xlsx";
loadFile(filePath);
}

public static void loadFile(String filePath) throws IOException
{
File file=new File(filePath);                                                     // Creating File Object
String fileExtension=FilenameUtils.getExtension(filePath);  // Getting extension of file
int totalRows=0;
Iterator<Row> rowIterator=null;

if(fileExtension.equalsIgnoreCase("xlsx"))
{
FileInputStream fis=new FileInputStream(file);
XSSFWorkbook doc =new XSSFWorkbook(fis);
XSSFSheet sheet=doc.getSheet("Sheet1");
        totalRows=sheet.getLastRowNum();
        rowIterator=sheet.rowIterator();
}
else if(fileExtension.equalsIgnoreCase("xls"))
{
FileInputStream fis =new FileInputStream(file);
HSSFWorkbook doc=new HSSFWorkbook(fis);
HSSFSheet sheet=doc.getSheet("Sheet1");
totalRows=sheet.getLastRowNum();
rowIterator=sheet.rowIterator();
}

System.out.println("Total Row Count : "+totalRows);
System.out.println("\nContent from document =>");
while(rowIterator.hasNext())
{
Iterator<Cell> cellIterator=rowIterator.next().cellIterator();
while(cellIterator.hasNext())
{
String cellData=cellIterator.next().toString();
System.out.print(cellData+"\t");
}
System.out.println();
}
}
}


Please do comment and share the post with your friends and colleagues. For any query or question, you can also email me at ashu.kumar940@gmail.com

Also, read How to read word document file using JAVA?

Other Blogs: 
https://agilehelpdoc.blogspot.in/

Thursday, August 17, 2017

How to perform Multiplication and Division without using * or / or % operators?

Question: How to perform Multiplication and Division without using * or / or % operators?

Problem: Write a code which can be used to Multiply or Divide two integer values without using "*" operator and "/" or "%" operators.

Example:
Inputs:-
          6 and 3 (Multiply)
          50 and 10 (Multiply)
          18 and 2 (Divide)
          39 and 4 (Divide)
Output:-
         Multiplication of 6 and 3 = 18
         Multiplication of 50 and 10 = 500
         Division of 18 and 6:
                Quotient 3 and Remainder 0
         Division of 39 and 4:
                Quotient 9 and Remainder 3

Answer:
We can achieve the same by using addition or subtraction as mentioned below:
1. Multiplication : 
                                    Multiplicand X Multiplier = Result
     Adding the 'Multiplicand' to itself for the value of 'Multiplier' times. As in above example if we have to get the result of 6 x 3 = ? then logic will be 6+6+6 = 18.
2. Division : 
                                  Dividend/Divisor = Quotient with Remainder   Subtract 'Divisor' from 'Dividend' along with a counter until the value of dividend gets greater than or equal to the divisor. As in above example if we have to get the result of 18 / 6 = ? then logic will be
18 - 6 = 12
12 - 6 = 6  
6 - 6 = 0    
As there are three iterations and the end result is zero, the answer will be 18 / 6 = Quotient 3 with remainder 0.

Code: 

public class DivisionMultiplication {

    public static void main(String[] args)
    {
        multiplication(6, 3);
        division(39,4);
   
    }

    public static void multiplication(int multiplicand, int multiplier)
    {
    // Step #1: Initialize a result variable with 0
        int result=0;
       
        // Step #2: Saving value of 'multiplier' into new variable 'initialMultiplier'
        int initialMultiplier=multiplier;
       
        // Step #3: Adding the 'multiplicand' in 'result' variable until 'multiplier' is 0.
        while(multiplier>0)
        {
        result+=multiplicand;
        multiplier--;
        }
       
        // Step #4: Use 'format()' of 'String' class to print the result
        String output=String.format("Multiplication of %s and %s = %s",multiplicand,initialMultiplier,result);
        System.out.println(output);
}

public static void division(int dividend, int divisor)
{
// Step #1: Initialize two variables 'result' and 'remainder' with 0.
int quotient=0;
int remainder=0;

// Step #2: Saving value of 'dividend' into new variable 'initialDividend'
int initialDividend=dividend;

// Step #3: Now subtract 'divisor' from 'dividend' until, value gets greater than or equal to divisor.
while(dividend>=divisor)
{
remainder=dividend-divisor;
dividend=remainder;
quotient++;
}

// Step #4: Use 'format()' of 'String' class to print the result
String output=String.format("Division of %s and %s =>",initialDividend,divisor);
        System.out.println(output);
        System.out.printf(" Quotient %s \n Remainder %s",quotient,remainder);
}
}




Please do comment and share the post with your friends and colleagues. For any query or question, you can also email me at ashu.kumar940@gmail.com

Other Blogs: 
https://agilehelpdoc.blogspot.in/

Friday, August 11, 2017

How to print Hello World as Olleh Dlrow in JAVA?

Question: Print Hello World as 'Olleh Dlrow'.

Problem: Write a program which reverses the each word in a sentence and also while printing first letter should be in upper case. Input can contain any number of words as mentioned below:


Input String:- 
             Hello World
             ask for help
            You Live Only Once

Output would be as:-
            Olleh Dlrow
            Ksa Rof Pleh
            Uoy Evil Ylno Ecno

Code:
public class ReverseWord
{

public static void main(String[] args)
{
// Step #1: Taking multiple Strings in the array.
String[] strArray={"Hello World","ask for help","You Live Only Once"};

for (String string : strArray)
{
reverseString(string);
}

}

public static void reverseString(String string)
{
// Step #2: Extracting words from a sentence.
String[] getWords=string.split(" ");

for (String word : getWords)
{
// Step #3: Getting reverse of each word.
String revString=new StringBuffer(word).reverse().toString();

// Step #4: Creating first letter in Upper case and rest in Lower case for each word.
revString=revString.substring(0, 1).toUpperCase()+revString.substring(1).toLowerCase();

// Step #5: Printing the expected Output
System.out.print(revString+" ");
}
System.out.println();
}
}


If anybody has any alternate solution please Post Your Answer in the comment box.

Please do comment and share the post with your friends and colleagues. For any query or question, you can also email me at ashu.kumar940@gmail.com.

Thursday, August 10, 2017

How to read word document(.doc or .docx) in JAVA?

Question: How to read word document(.doc or .docx) in JAVA?

Reference Documents:
tempdata.doc
tempdata_1.docx

Problem:
1. The user can enter word document in any format(extension like .doc or .docx) as mentioned above.
2. Identify the extension of word file.
3. Reading and print all the content of the word file on Console.

Answer:-
Step #1 Create two word documents, one with tempdata.doc and other with tempdata_1.docx extensions.
Step #2 Now download and add the jar files in your java project as mentioned in the 'Reference Jar Files' section.
Step #3 Copy and paste the code in your class file and run the code to observe the output.
Step #4 To identify the extension of the word file we have used the getExtension() method of FilenameUtils Class as mentioned below:
                               String fileExtension= FilenameUtils.getExtension(filePath);
Step #5 Once we get the file extension, we have to call correct method accordingly.
Step #6 For the file with the extension ".docx" we have to use XWPFDocument and XWPFParagraph Classes.
                               XWPFDocument doc =new XWPFDocument(FileInputStream fis);
                               List<XWPFParagraph> getDocParagraphs= doc.getParagraphs();
Step #7 For the file with the extension ".doc" we have to HWPFDocument and WordExtractor classes.
                               HWPFDocument doc=new HWPFDocument(FileInputStream fis);
                              WordExtractor extractor=new WordExtractor(doc);
Note: Please change the path of the Word document file accordingly.

Reference Jar files:
1. Navigate to :- poi-bin-3.16-20170419.tar.gz
2. Click on the first link, poi-bin3.16-20170419.tar.gz link.
3. Jar files get downloaded automatically.
4. Add the jar files in your Project using 'configure build path' option.

Code:

package word;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

public class WordHandling
{
public static void main(String[] args) throws IOException
{
String filePath="input_Word//tempdata_1.doc";               // Location of word document file.
loadFile(filePath);
}

public static void loadFile(String filePath) throws IOException
{
File file=new File(filePath);                                                     // Creating File Object
String fileExtension=FilenameUtils.getExtension(filePath);  // Getting extension of files.
if(fileExtension.equalsIgnoreCase("docx"))
{
readDocxFile(file);
}
else if(fileExtension.equalsIgnoreCase("doc"))
{
readDocFile(file);
}
}

// Reading data from ".docx" file.
public static void readDocxFile(File file) throws IOException
{
FileInputStream fis=new FileInputStream(file);
XWPFDocument doc =new XWPFDocument(fis);                                                      
                // Getting all the paragraphs from the document and adding the same in ArrayList List<XWPFParagraph> getDocParagraphs= doc.getParagraphs();

                // Getting a total number of paragraphs in the word document.
int totalParagraphs=getDocParagraphs.size();        
System.out.println("Total number of paragraphs : "+totalParagraphs);

                // Print document content on Console.
for (XWPFParagraph currentParagraph : getDocParagraphs)
{
System.out.println(currentParagraph.getText().toString());
}
doc.close();
}

// Reading data from ".doc" file.
public static void readDocFile(File file) throws IOException
{
FileInputStream fis =new FileInputStream(file);
HWPFDocument doc=new HWPFDocument(fis);

WordExtractor extractor=new WordExtractor(doc);
                // Getting all the paragraphs from the document and adding the same in String array.
String[] getDocParagraphs= extractor.getParagraphText();

                // Getting total number of paragraphs in word document.
int totalParagraphs=getDocParagraphs.length;
System.out.println("Total count of paragraphs : "+totalParagraphs+"\n");

                // Print document content on Console.
for (String currentPara : getDocParagraphs)
{
System.out.print(currentPara);
}
extractor.close();
}
}

Please do comment and share the post with your friends and colleagues. For any query or question, you can also email me at ashu.kumar940@gmail.com.

Other Blogs:
https://agilehelpdoc.blogspot.in/