skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Tuesday, October 23, 2012

Compare two files using Java

Posted by Raju Gupta at 2:11 AM – 0 comments
 

The program will prompt for 2 file names(.txt) that are to be compared. Given the file names, this program will compare the two files.

If any difference is there, it will print the differences and no. of differences in command prompt. 

If no difference is there, it will print
"files are equal".

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

//defining class

public class myfilereader
{
//defining main function
 public static void main (String[] args) throws java.io.IOException
    {
  //Getting the name of the files to be compared.
  BufferedReader br2 = new BufferedReader (new
InputStreamReader(System.in));
  System.out.println("Enter 1st File name:");
    String str = br2.readLine();
    System.out.println("Enter 2nd File name:");
    String str1 = br2.readLine();

  String s1="";
    String s2="",s3="",s4="";
    String y="",z="";

        //Reading the contents of the files
   BufferedReader br = new BufferedReader (new FileReader (str));
    BufferedReader br1 = new BufferedReader (new FileReader (str1));

   while((z=br1.readLine())!=null)
    s3+=z;

  while((y=br.readLine())!=null)
     s1+=y;

  System.out.println ();

        //String tokenizing
    int numTokens = 0;
    StringTokenizer st = new StringTokenizer (s1);
    String[] a = new String[10000];
    for(int l=0;l<10000;l++)
      {a[l]="";}
    int i=0;
    while (st.hasMoreTokens())
      {
        s2 = st.nextToken();
          a[i]=s2;
   i++;
            numTokens++;
      }

      int numTokens1 = 0;
     StringTokenizer st1 = new StringTokenizer (s3);
     String[] b = new String[10000];
     for(int k=0;k<10000;k++)
      {b[k]="";}
     int j=0;
     while (st1.hasMoreTokens())
       {
        s4 = st1.nextToken();
        b[j]=s4;
        j++;
        numTokens1++;
       }

//comparing the contents of the files and printing the differences, if any.
  int x=0;
      for(int m=0;m<a.length;m++)
      {
   if(a[m].equals(b[m])){}
    else
    {
     x++;
  System.out.println(a[m] + " -- " +b[m]);
  System.out.println();}
      }
 System.out.println("No. of differences : " + x);
 if(x>0){System.out.println("Files are not equal");}
 else{System.out.println("Files are equal. No difference found");}

 }
}

[ Read More ]
Read more...
Monday, October 22, 2012

Jasper report as pdf

Posted by Raju Gupta at 8:00 PM – 0 comments
 
prints the report in pdf format.

//import it in the java file

import net.sf.jasperreports.engine.JasperExportManager;
// a function ehich calls the jasper to generate the report
private String generatePldbbyCC(ParameterReportCriteria prcObject, Map reportMap) throws Exception {
 JasperPrint jasperPrint = null;
 JRFileVirtualizer virtualizer = null;
 String destFileLoc = null;
 File sourceFile = null;
 File destFile = null;
 ESpecDAOController control = new ESpecDAOController();
 // puts the parameters to jasper.
 parameters.put(Constants.COMPETITIVE_CATEGORIES, prcObject.getSelectedCompCategs()); 
 parameters.put("REPORT_CONNECTION", control.getMasterConnection());
 parameters.put(EspecConstants.CURR_TIME, "Exported: " + new SimpleDateFormat("M/d/yyyy 'at' hh:mm:ss a").format(DateUtil.getCurrentDateTime()));

 PropertiesVO templatePath = setJasperpath();

 virtualizer = new JRFileVirtualizer(1, templatePath.getValue());

 parameters.put(SUBREPORT_DIR, templatePath.getValue());

 parameters.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);

 try {

  jasperPrint = JasperFillManager.fillReport(templatePath.getValue() + "/sample.jasper", parameters, control.getMasterConnection());

 } else {
  //get the file with extension as pdf
  destFile = new File(templatePath.getValue(), jasperPrint.getName() + "_" + prcObject.getProcessId() + ".pdf");

 } 

 destFileLoc = destFile.toString();
 //exports the report as pdf.
 JasperExportManager.exportReportToPdfFile(jasperPrint,destFileLoc);


[ Read More ]
Read more...

Finding the difference between two images using their samples

Posted by Raju Gupta at 12:00 PM – 0 comments
 
Helps in finding the difference between two images by obtaining their samples and comparing them. The number of bands assosiated with each image is also compared, along with their width and height.

File file1 = new File("C:\Documents and Settings\515956\Desktop\Raj_image.jpg"); 
File file2 = new File("C:\Documents and Settings\515956\Desktop\Local_image.jpg");  
BufferedImage image1 = ImageIO.read(file1); 
BufferedImage image2 = ImageIO.read(file2);

Raster r1 = image1.getData();
Raster r2 = image2.getData(); 
boolean ret; // Stores result. 
// Check image sizes and number of bands. If there are different
// then no need to compare images as they are definitely not equal. 

System.out.println("image1 band"+r1.getNumBands()+"  image2 band"+r2.getNumBands()+"  image1 width"+r1.getWidth()+"  image2 width"+ r2.getWidth()+"  image1 height"+ r1.getHeight()+"  image2 height"+r2.getHeight()); 

if (r1.getNumBands() != r2.getNumBands() ||   r1.getWidth() != r2.getWidth() ||   r1.getHeight() != r2.getHeight()) {  
 ret = false;
 System.out.println("Primary comparison failure");

} 

else {  
 // #Bands and image bounds match so compare each sample in turn. 
 ret = true;   
 search:   
  for (int i=0; i<r1.getNumBands(); ++i) { 
   for (int x=0; x<r1.getWidth(); ++x) {    
    for (int y=0; y<r1.getHeight(); ++y) {  


     if (r1.getSample(x, y, i) != r2.getSample(x, y, i)) {     
      // At least one sample differs so result is false; 
      ret = false; 
      System.out.println("sample difference");
      // Use labeled break to terminate all loops.
      break
      search;   
     }   
    }    
   }   
  }   

}
System.out.println(ret);

[ Read More ]
Read more...

Preventing CRLF injection

Posted by Raju Gupta at 5:30 AM – 0 comments
 
This code will encode your data if a user tries to attack your application through CRLF injection

String s=Arrays.toString(object);
if(s.contains("/") || s.contains(">")||s.contains("<")||s.contains("?") ||s.contains("&") ||s.contains(""))
{
 String validobject=URLEncoder.encode(s);
 System.out.println("the encoded data is"+validobject);
}
else
{
 System.out.println("the non-encoded data is"+object);
}


[ Read More ]
Read more...

Send a mail from SMTP server using Java Mail

Posted by Raju Gupta at 1:55 AM – 0 comments
 
This code allows the user to login to his/her mail account to send a mail to another recepient.First the code needs to be configured by entering the Server details and user credentials .This code authenticates the user and creates a session then a MimeMessage Object is created where the subject and content of the mail is set.

public class SmtpMail{
 public static void main(String[] args) 
 {
  Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");
  final String username = "Username@gmail.com";
  final String password = "Password";
  Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
 protected PasswordAuthentication getPasswordAuthentication() {
   return new PasswordAuthentication(username, password);
  }
  });
try {
   Message message = new MimeMessage(session);
   message.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse("toEmailAddress@yahoo.com"));
   System.out.println(session.toString());
   message.setSubject("JavaMail Subject");
   message.setText("Dear Recepient,"
    + "\n\n This is a Test Mail");
   System.out.println(session.toString());
   Transport.send(message);
   System.out.println("Done");
 
  } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
 }
}


[ Read More ]
Read more...
Sunday, October 21, 2012

Creating JSON using Java

Posted by Raju Gupta at 9:30 PM – 0 comments
 
This is used to create JSON objects using Java

import org.json.JSONObject;
//Creating JSON object
JSONObject json = new JSONObject();
//Put tag name and value to the object
json.put("city", "Mumbai");
json.put("country", "India");

String output = json.toString();

[ Read More ]
Read more...

Getting Timezone based Timestamp

Posted by Raju Gupta at 1:00 PM – 0 comments
 
It is used to find the Timestamp based on the given Timezone

//Creating format based on the need
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//Set the Timezone 
dateFormat.setTimeZone(clientTimeZone);
String clientTime = dateFormat.format(date);
Date date2 = new Date(clientTime);
//
System.out.println(date2);

[ Read More ]
Read more...
Newer Posts Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • Comparison of Two Variable using If | JAVA Program
    Here is a Java Program to show Comparison Operation on the two variable using If Control Structure class IfComparison { public static vo...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Java Utility program
    The java utility program is used to Read from a properties file,make DB connections,read from a file and Write into a file. import java.s...
  • CheckSum Login in java
    A Checksum is used for error checking while transferring data from server to server or client to server. Data is flown across networks in t...
  • Alphanumeric String Sorting using Java
    Alphanumeric is a combination of alphabetic and numeric characters (sometimes shortened to alphameric). In computing, the alphanume...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • How to swap two numbers using only two variables in Java
     Here's a program to swap two numbers using only two variables with explanation using Java Programming language.
  • Define a class to represent a length measured in meters, centimeters, and millimeters | Java Program
    Define a class, mcmLength, to represent a length measured in meters, centimeters, and millimeters, each stored as integers. Include methods...
  • Sorting a List in ascending order
    This code snippet sorts a list of objects based on the value of a field of those objects import java.util.ArrayList; import java.util...
Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • Creating Dynamic Macro Enabled Excel by Java
    We can create a dynamic macro enabled excel by java: We need to create a excel sheet template with macro on server. we can copy the...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Java Class to Calculate the Volume of Box
    Here is a Java Class to Calculate the Volume of Box. class Box { double width; double height; double depth; // This is the con...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger