Pages

Showing posts with label CORE JAVA. Show all posts
Showing posts with label CORE JAVA. Show all posts

Wednesday, 30 April 2014

Scanner Example With Simple Java Code

Hello friends this is a very basic example of Scanner to use as take user input from screen using java.

Here is the code :

import java.util.Scanner;
public class GettingUserInput {

    public static void main(String[] args) {
            Scanner var = new  Scanner(System.in);
            System.out.println("You have entred : "+ var.nextLine());
    }
}


NEED ONE CLICK ON DISPLAYED ADVERTISEMENT TO CONTRIBUTE THIS BLOG

Tuesday, 1 April 2014

How to get All IP address of given host name using Java

Below example shows how to get list of all IPs for the given host. By passing host name to InetAddress.getAllByName() method, you can get list of InetAddress objects. You have to call getHostAddress() method on each object to get all list of IPs.

HERE IS THE CODE :
-------------------------

import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetAllIPsOfHostName {

public static void main(String[] args) {
try {
           InetAddress[] myHost = InetAddress.getAllByName("www.google.com");
           for(InetAddress host:myHost){
               System.out.println(host.getHostAddress());
           }
       } catch (UnknownHostException ex) {
           ex.printStackTrace();
       }

}

}


KEEP SHARING KNOWLEDGE

How to get host property using Java

HERE IS THE CODE :
-------------------------

import java.net.MalformedURLException;
import java.net.URL;

public class GetHostProperty {


public static void main(String[] args) {
try {
            String url =
"https://mail.google.com/mail/?tab=jm&pli=1#inbox/1450ef3ef801473e";
            URL myUrl = new URL(url);
            System.out.println("Protocol: "+myUrl.getProtocol());
            System.out.println("Host: "+myUrl.getHost());
            System.out.println("Port: "+myUrl.getPort());
            System.out.println("Athority of the URL: "+myUrl.getAuthority());
            System.out.println("Query: "+myUrl.getQuery());
            System.out.println("Reference: "+myUrl.getRef());
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }

}

}


KEEP SHARING KNOWLEDGE

How to get host-name from IP address using Java

HERE IS THE CODE :
-------------------------

import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPAddressToHostName {

public static void main(String[] args) {
try {
InetAddress host = InetAddress.getByName("74.125.236.146");
System.out.println(host.getHostName());
} catch (UnknownHostException ex) {
ex.printStackTrace();
}
}

}

KEEP SHARING KNOWLEDGE

Monday, 31 March 2014

Java JDBC Connection with MySql Simple Example

Hello friends , this is a very simple Java program for connecting your MySql Database with Java using Java code...

Here is the code :
------------------------

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
 
public class JDBCExample {
 
  public static void main(String[] argv) {
 
 System.out.println("-------- MySQL JDBC Connection Testing --------");
 
 try {
  Class.forName("com.mysql.jdbc.Driver");
 } catch (ClassNotFoundException e) {
  System.out.println("Where is your MySQL JDBC Driver?");
  e.printStackTrace();
  return;
 }
 
 System.out.println("MySQL JDBC Driver Registered!");
 Connection connection = null;
 
 try {
  connection = DriverManager.getConnection("jdbc:mysql://localho                st:3306/dbname","root", "password");
 
 } catch (SQLException e) {
  System.out.println("Connection Failed! Check output console");
  e.printStackTrace();
  return;
 }
 
 if (connection != null) {
  System.out.println("Connection established.");
 } else {
  System.out.println("Failed to make connection!");
 }
  }
}

How to get local computer OS and IP address related detail using Java code

Hello friends this is a very simple Java Program to get your local computer OS related information and IP address related information...

Here is the code:
------------------------

import java.net.InetAddress;

public class GetDayOfWeekOfAnyDate {

public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
System.out.println("Using InetAddress");
System.out.println("Host Address: " + address.getHostAddress());
System.out.println("Host Name: " + address.getHostName());
System.out.println("CanonicalHostName: "
+ address.getCanonicalHostName());
System.out.println("Address: " + address.getAddress());
System.out.println("LocalHost: " + address.getLocalHost());
System.out.println("LoopbackAddress: "
+ address.getLoopbackAddress());

String os = "os.name";
String version = "os.version";
String arch = "os.arch";
System.out.println("Name of the OS: " + System.getProperty(os));
System.out.println("Version of the OS: "
+ System.getProperty(version));
System.out.println("Architecture of the OS: "
+ System.getProperty(arch));
} catch (Exception e) {
e.printStackTrace();
}

}

}


KEEP SHARING THE KNOWLEDGE

Sunday, 23 March 2014

Number To Word Using Java ( FOR NEGATIVE , POSITIVE, FRACTIONAL VALUES )

HI FRIENDS THIS IS A VERY SIMPLE PROGRAM THAT WILL CONVERT DECIMAL NUMBER TO IT'S EQUIVALENT AMOUNT IN WORDS.

import java.util.Scanner;

public class NumToWord {

String string;
String st1[] = { "", "one", "two", "three", "four", "five", "six", "seven","eight", "nine", };
String st2[] = { "hundred", "thousand", "lakh", "crore" };
String st3[] = { "ten", "eleven", "twelve", "thirteen", "fourteen",
         "fifteen", "sixteen", "seventeen", "eighteen", "ninteen", };
String st4[] = { "twenty", "thirty", "fourty", "fifty", "sixty", "seventy","eighty", "ninty" };

public String convert(int number) {
int n = 1;
int word;
string = "";
while (number != 0) {
switch (n) {
case 1:
word = number % 100;
pass(word);
if (number > 100 && number % 100 != 0) {
show("and ");
}
number /= 100;
break;

case 2:
word = number % 10;
if (word != 0) {
show(" ");
show(st2[0]);
show(" ");
pass(word);
}
number /= 10;
break;

case 3:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[1]);
show(" ");
pass(word);
}
number /= 100;
break;

case 4:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[2]);
show(" ");
pass(word);
}
number /= 100;
break;

case 5:
word = number % 100;
if (word != 0) {
show(" ");
show(st2[3]);
show(" ");
pass(word);
}
number /= 100;
break;

}
n++;
}
return string;
}

public void pass(int number) {
int word, q;
if (number < 10) {
show(st1[number]);
}
if (number > 9 && number < 20) {
show(st3[number - 10]);
}
if (number > 19) {
word = number % 10;
if (word == 0) {
q = number / 10;
show(st4[q - 2]);
} else {
q = number / 10;
show(st1[word]);
show(" ");
show(st4[q - 2]);
}
}
}

public void show(String s) {
String st;
st = string;
string = s;
string += st;
}

public static void main(String[] args) {
NumToWord w = new NumToWord();
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter Number: ");
String num = input.nextLine();
int num2 = 0;
boolean isMinus = false;

if (num.indexOf(".") == -1) {
if (num.charAt(0) == '-') {
String num3 = num.substring(1);
isMinus = true;
num2 = Integer.parseInt(num3);
} else {
num2 = Integer.parseInt(num);
}
String inwords = w.convert(num2);
if (isMinus) {
System.out.println("minus " + inwords);
} else {
System.out.println(inwords);
}
} else {
String part1 = num.substring(0, num.indexOf("."));
String part2 = num.substring(num.indexOf(".")+1);
if (part1.charAt(0) == '-') {
String num3 = part1.substring(1);
isMinus = true;
num2 = Integer.parseInt(num3);
} else {
num2 = Integer.parseInt(part1);
}
String inwords1 = w.convert(num2);
String inwords2 = w.convert(Integer.parseInt(part2));
if (isMinus) {
System.out.println("minus " + inwords1 + " point "+ inwords2);
} else {
System.out.println(inwords1 + " point "+ inwords2);
}
}
} catch (Exception e) {
System.out.println("Not a valid number.");
}
}
}


=======================================================================
* CONVERT ALL DECIMAL WITH FRACTIONAL PART AS WELL AS MINUS VALUE.
=======================================================================

Saturday, 22 February 2014

How to find out number of folders in directory using Java

SIMPLE JAVA PROGRAM TO FIND OUT NUMBER OF FOLDERS IN DIRECTORY

CODE :


import java.io.File;

public class NumberOfFileInFolder {
          public static void main(String[] args) {
File f1 = new File("D:/SONGS");
                int count1 = 0;
                for (File file : f1.listFiles()) {
                   if (file.isDirectory()) {
                        count1++;
                   }
               }
               System.out.println("Number of directories: " + count1); // Show number of directory only
}
}

How to find out no of files in directory using Java code

SIMPLE JAVA PROGRAM TO KNOW NUMBER OF FILES IN DIRECTORY

CODE :

import java.io.*;
 
public class CountFilesInDirectory {
        public static void main(String[] args) {
                File f = new File("D:/SONGS");
                int count = 0;
                for (File file : f.listFiles()) {
                        if (file.isFile()) {
                                count++;
                        }
                }
                System.out.println("Number of files: " + count);
                // Also do it with bellow one line code...
                System.out.println(new File("D:/SONGS").listFiles().length);
        }
}

Wednesday, 19 February 2014

Java Program To Shutdown Computer

This is a simple Java program for shutdown the computer.

This program is used when you make a application that will run for an hour and you don't wait to shutdown your computer, just add this code at last of your application. Your computer will automatically shutdown when your application is over. You can use it more place also.


Here is the code :
------------------------------------------------------------------------------------------------------------
public class ShutdownComputer {

    public static void main(String[] args) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Process proc = runtime.exec("shutdown -s -t 30"); // after 30 second it will shoutdown
        System.exit(0);

    }
}
--------------------------------------------------------------------------------------------------------------

COMMENT IF YOU HAVE ANY COMPUTER TRICKS.

Wednesday, 1 January 2014

GET FILE SIZE IN KB OR MB USING JAVA

This is a simple practical demo to find out size of file in KB and MB.

 GetFileSize.java

import java.io.File;
import java.text.DecimalFormat;

public class GetFileSize {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        File file = new File("D:/C++ The Complete Reference 4th Ed.pdf");
        long filesize = file.length();
        double size_in_kb = ((filesize / 1024));
        double size_in_mb = size_in_kb / 1024;
        if (size_in_kb < 1024) {
            System.out.println("File Size : " + size_in_kb + " KB");
        } else {
            System.out.println("File Size : " + Double.parseDouble(new DecimalFormat("##.##").format(size_in_mb))+" MB ");
        }
    }

}

======================================================================

Tuesday, 31 December 2013

GET NUMBER OF PAGE OF PDF FILE USING iTEXT DEMO

For perform this practical you need itext java API. Download it from iText official website.

A simple practical that will count the total number of pages of any pdf file. This may use in e-library like application that i already use.


CountPDFPage.java

import com.itextpdf.text.pdf.PdfReader;

public class CountPDFPage {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        PdfReader reader;
        try {
            reader = new PdfReader("D:\\jreports.pdf");
            int page = reader.getNumberOfPages();
            System.out.println("Number Of pages : "+page); // IT WILL RESULT 339 AS A NUMBER OF TOTAL PDF PAGES.
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }

SENDING HTML PAGE AS A EMAIL USING GMAIL SMTP

Main.java

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
         String[] recipients = new String[]{"maheshwarianand@ymail.com"}; 
            String[] bccRecipients = new String[]{"anandmaheshwari15790@gmail.com"}; 
            String subject = "Hi this is test Mail"; 
            String messageBody = "Test Mail from codesstore.blogspot.com"; 
     
            new MailUtil().sendMail(recipients, bccRecipients, subject, messageBody); 
    }

}



MainUtil.java

import java.io.UnsupportedEncodingException; 
import java.util.Properties; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator; 
import javax.mail.BodyPart;
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage; 
import javax.mail.internet.MimeMultipart;
 
public class MailUtil { 
 
    private String SMTP_HOST = "smtp.gmail.com"; 
    private String FROM_ADDRESS = "sender_mail@gmail.com"; 
    private String PASSWORD = "mail_password"; 
    private String FROM_NAME = "Anand"; 
 
    public boolean sendMail(String[] recipients, String[] bccRecipients, String subject, String message) { 
        try { 
            Properties props = new Properties(); 
            props.put("mail.smtp.host", SMTP_HOST); 
            props.put("mail.smtp.auth", "true"); 
            props.put("mail.debug", "false"); 
            props.put("mail.smtp.ssl.enable", "true"); 
 
            Session session = Session.getInstance(props, new SocialAuth()); 
           
           
            Message msg = new MimeMessage(session); 
           
           
 
            InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME); 
            msg.setFrom(from); 
 
            InternetAddress[] toAddresses = new InternetAddress[recipients.length]; 

           
            for (int i = 0; i < recipients.length; i++) { 
                toAddresses[i] = new InternetAddress(recipients[i]); 
            } 
           
            msg.setRecipients(Message.RecipientType.TO, toAddresses); 
 
 
            InternetAddress[] bccAddresses = new InternetAddress[bccRecipients.length]; 
            for (int j = 0; j < bccRecipients.length; j++) { 
                bccAddresses[j] = new InternetAddress(bccRecipients[j]); 
            } 
            msg.setRecipients(Message.RecipientType.BCC, bccAddresses); 
 
            msg.setSubject(subject); 
           
            //
            // This HTML mail have to 2 part, the BODY and the embedded image
            //
            MimeMultipart multipart = new MimeMultipart("related");

            // first part  (the html)
            BodyPart messageBodyPart = new MimeBodyPart();
            String htmlText = "<center><H1>Hello</H1></center><img src=\"cid:image\">";
            messageBodyPart.setContent(htmlText, "text/html");

            // add it
            multipart.addBodyPart(messageBodyPart);
           
            // second part (the image)
            messageBodyPart = new MimeBodyPart();
            DataSource fds = new FileDataSource
              ("D:\\a.jpg");
            messageBodyPart.setDataHandler(new DataHandler(fds));
            messageBodyPart.setHeader("Content-ID","<image>");

            // add it
            multipart.addBodyPart(messageBodyPart);
           
           
            //msg.setContent(message, "text/plain"); 
           
            msg.setContent(multipart);
            Transport.send(msg); 
           
            System.out.println("Sendded Successfully...");
            return true; 
        } catch (UnsupportedEncodingException ex) { 
            Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex); 
            return false; 
 
        } catch (MessagingException ex) { 
            Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex); 
            return false; 
        } 
    } 
 
    class SocialAuth extends Authenticator { 
 
        @Override 
        protected PasswordAuthentication getPasswordAuthentication() { 
 
            return new PasswordAuthentication(FROM_ADDRESS, PASSWORD); 
 
        } 
    } 
} 

=====================================================================

Saturday, 28 December 2013

SEND EMAIL IN JAVA WITH gmail SMTP



Send a mail using JAVA mail API with gmail smtp server.
You need mail.jar JAVA API file. You can download it from oracle-java site.  

MailUtil.java

import java.io.UnsupportedEncodingException; 
import java.util.Properties; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.mail.Authenticator; 
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeMessage; 
 
public class MailUtil { 
 
    private String SMTP_HOST = "smtp.gmail.com"; 
    private String FROM_ADDRESS = "sender_mail@gmail.com"; 
    private String PASSWORD = "***********"; 
    private String FROM_NAME = "Anand"; 
 
    public boolean sendMail(String[] recipients, String[] bccRecipients, String subject, String message) { 
        try { 
            Properties props = new Properties(); 
            props.put("mail.smtp.host", SMTP_HOST); 
            props.put("mail.smtp.auth", "true"); 
            props.put("mail.debug", "false"); 
            props.put("mail.smtp.ssl.enable", "true"); 
 
            Session session = Session.getInstance(props, new SocialAuth()); 
            Message msg = new MimeMessage(session); 
 
            InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME); 
            msg.setFrom(from); 
 
            InternetAddress[] toAddresses = new InternetAddress[recipients.length]; 
            for (int i = 0; i < recipients.length; i++) { 
                toAddresses[i] = new InternetAddress(recipients[i]); 
            } 
            msg.setRecipients(Message.RecipientType.TO, toAddresses); 
 
 
            InternetAddress[] bccAddresses = new InternetAddress[bccRecipients.length]; 
            for (int j = 0; j < bccRecipients.length; j++) { 
                bccAddresses[j] = new InternetAddress(bccRecipients[j]); 
            } 
            msg.setRecipients(Message.RecipientType.BCC, bccAddresses); 
 
            msg.setSubject(subject); 
            msg.setContent(message, "text/plain"); 
            Transport.send(msg); 
            System.out.println("Sendded Successfully...");
            return true; 
        } catch (UnsupportedEncodingException ex) { 
            Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex); 
            return false; 
 
        } catch (MessagingException ex) { 
            Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex); 
            return false; 
        } 
    } 
 
    class SocialAuth extends Authenticator { 
 
        @Override 
        protected PasswordAuthentication getPasswordAuthentication() { 
 
            return new PasswordAuthentication(FROM_ADDRESS, PASSWORD); 
 
        } 
    } 
} 


Main.java

public class Main {

       /**
        * @param args
        */
       public static void main(String[] args) {
              // TODO Auto-generated method stub
               String[] recipients = new String[]{"maheshwarianand@ymail.com"}; 
               String[] bccRecipients = new String[]{"sender_mail@gmail.com"}; 
               String subject = "Hi this is test Mail"; 
               String messageBody = "Test Mail from morecomputerscience.blogspot.com"; 
        
               new MailUtil().sendMail(recipients, bccRecipients, subject, messageBody); 
       }

}


=======================================================================