Showing posts with label core Java. Show all posts
Showing posts with label core Java. Show all posts

Wednesday, February 29, 2012

use jdk 1.6 to compile the java file as jdk1.3

assert is a keyword introduce at jdk 1.4,You cannot use it as an identifier in jdk1.4 +.
However if you have used it as an identifier,and you want to compile the class,then you need to go back to jdk 1.3.

But you have only jdk 1.6 with you.Still then you can compile your java class,as if you are using jdk 1.3

 Demo.java
 public class Demo
{
public static void main(String[] args) 
{
 boolean assert = true;
if(assert) System.out.println("if is true");
}
}



compile using jdk 1.4+ will give you these error

-------------------------------------------------
>javac Demo.java
Demo.java:5: as of release 1.4, 'assert' is a keyword, and may not be used as an
 identifier
(use -source 1.3 or lower to use 'assert' as an identifier)
                 boolean assert = true;
                         ^
Demo.java:6: as of release 1.4, 'assert' is a keyword, and may not be used as an
 identifier
(use -source 1.3 or lower to use 'assert' as an identifier)
                if(assert) System.out.println("if is true");

To compile as jdk1.3 although you are using jdk 1.4+
--------------------------------------------------------
>javac -source 1.3 Demo.java

Friday, February 17, 2012

Running javaProgram without main() not possible in JDK1.7 latest Version

Running Java Program without main() has become an old story now.
So far we used to write the program like this
StaticDemo.java
public class StaticDemo
{
   static
    { 
        System.out.println("Hello");
        System.out.exit(0); 
     }
}
And then >javac *.java
>java StaticDemo

It compiles and runs successfully,printing Hello

This works well in JDK1.7 old versions(build 1.7.0-ea-b19)

But From jdk 1.7(build1.7.0-ea-b85),It gives run time Exception

Error: Main method not found in class StaticDemo, please define the main method
   public static void main(String[] args)


The latest version while writing this article was build  jdk 1.7(build 1.7.0_03-b05),which also doesnot allow running java program without main();

So the Concept is:
When we say
java StaticDemo
Compiler understands that we are trying to execute the program,so before executing the static block,it first checks whether main() is there or not.If not,throws Exception

Friday, February 10, 2012

Creating a Formatted XML using Java

Lets Assume we want to create an XML file,
Eg:-

CreatXMLFile.java
----------------------
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class CreatXMLFile
{  
public static void main(String[] args) throws Exception
 {   
    //creating factory
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    //creating a builder
    DocumentBuilder documentBuilder =documentBuilderFactory.newDocumentBuilder(); 
    //creating a document
    Document document = documentBuilder.newDocument();
   
    String root = "SMS";

    //adding root Element
    Element rootElement = document.createElement(root);
    rootElement.setAttribute("area", "hyderabad");

    document.appendChild(rootElement); //adds <SMS> as root element

    String element ="Number";    
    String data = "12345";
   
    Element em = document.createElement(element);
    em.appendChild(document.createTextNode(data));
    rootElement.appendChild(em);  //creates <Number>12345</Number> and adds to root element<SMS>
/*
<SMS>
<Number>12345</Number>
</SMS>
*/
  
    element ="message";   
    data= "hello";
  
    em = document.createElement(element);  
    em.appendChild(document.createTextNode(data));
    rootElement.appendChild(em); //creates <message>hello</message> and adds to root element<SMS>
/*
<SMS>
<Number>12345</Number>
<message>hello</message>
</SMS>
*/
  
  
    em=document.createElement("delivered");
    Element childElement = document.createElement("status");
    childElement.appendChild(document.createTextNode("failed"));
    em.appendChild(childElement);
    rootElement.appendChild(em);//creates <delivered><status> failed</status></delivered> and adds to root element<SMS>

 /*<SMS>
<Number>12345</Number>
<message>hello</message>
<delivered>
      <status> failed</status>
</delivered>
</SMS>
    */
   
    //Used to Write the generated xml structure to  file or system console
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");//arrange the xml in an idented format
    DOMSource source = new DOMSource(document);   
    File f=new File("d:/myfile.xml");
   
    StreamResult result =  new StreamResult(f);  //prints xml into file
    //StreamResult result =  new StreamResult(System.out);   
    transformer.transform(source, result);
 
 }
 }

Wednesday, January 4, 2012

Sending SMS to your Mobile Through Java Program

Yes,we can send SMs Using our Java Program.These are the steps
Note:Ipipi allows you to send only 5 sms free of cost,After that create one more account
1> create an account in http://www.ipipi.com/
2>I created Account like this:
username:  surajSMS
password: suraj123

3>Prepare the program in this way





-------------------------------------------------------------------------------------------------
SendSMS.java
 ------------------------------------------------------------------------------------------------
import java.io.*;                                                                                   
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendSMS {

    public SendSMS() {
    }
   //create an account on ipipi.com with the given username and password
    public void msgsend() {
        String username = "surajSMS";  //Your Credentials
        String password = "suraj123";
        String smtphost = "ipipi.com";      //Ip/Name of Server
        String compression = "None";       //I dont want any compression
        String from = "surajSMS@ipipi.com";    //ur userid@ipipi.com
        //This mobile number need not be registered with ipipi.com
        String to = "919861098610@sms.ipipi.com";    //mobile number where u want to send sms
        String body = "Hi This Msg is sent through Java Code";
        Transport tr = null;

        try {
         Properties props = System.getProperties();
         props.put("mail.smtp.auth", "true");

         // Get a Session object
         Session mailSession = Session.getDefaultInstance(props, null);

         // construct the message
         Message msg = new MimeMessage(mailSession);

         //Set message attributes
         msg.setFrom(new InternetAddress(from));
         InternetAddress[] address = {new InternetAddress(to)};
         msg.setRecipients(Message.RecipientType.TO, address);
         msg.setSubject(compression);
         msg.setText(body);
         msg.setSentDate(new Date());

         tr = mailSession.getTransport("smtp");
         //try to connect
         tr.connect(smtphost, username, password);
         msg.saveChanges();
         //send msg to all recipients
         tr.sendMessage(msg, msg.getAllRecipients());
         tr.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
    }

      public static void main(String[] argv) {
         SendSMS sms = new SendSMS();
          sms.msgsend();
          System.out.println("Successfull");
      }
}


Download Source Here

Wednesday, December 21, 2011

Get All the Files and Folders Present inside the Directory

This is one of the way to get the list of all the files and folders present inside a particular folder,
I assume here that you have C:\store  folder in your computer with some subfolders and files inside it.


import java.io.File;
import java.io.IOException;

public class GetAllFilesAndFoldersInDirectory
{
public static void main(String[] args) throws IOException
{
File dir = new File("c:/store");
//All the files and folder names inside C:/store will be stored in this array
String[] list = dir.list();

if (list == null)
{
    // Either dir does not exist or is not a directory
}
else
{
    for (int i=0; i<list.length; i++)
    {
        // Get filename of file or directory
        String filename = list[i];
        System.out.print(filename+"::");
       
        //check if its a file or directory
        File tf = new File(dir.getPath(), list[i]);
        if (tf.isDirectory())
          System.out.println("directory");
          else System.out.println("file");
   
     }//for
}//else
}//main
}//class

Tuesday, December 20, 2011

Create Folders SubFolders using Java

CreateDirectory.java
-------------------------------------------------------------------------------------------------------
import java.io.*;
class CreateDirectory
{
 public static void main(String args[])
  {
  try{
  String myfolder ="c:/test";
  String mySubFolder1="c:/test/dir1";
  String mySubFolder2="c:/test/dir2";
  String mySubFolder3="c:/test/dir3/dir4/dir5";
  // Create folder test under c:
  //return true if created successfully
 
  boolean success = (new File(myfolder)).mkdir();
 
  //create a file inside that folder,returns true if successful
  success = new File("c:/test/myfile.txt").createNewFile();
 
 
  // Create multiple folders inside test
  success = (new File(mySubFolder1)).mkdir();
  success = (new File(mySubFolder2)).mkdir();
  success = (new File(mySubFolder3)).mkdirs();
 
 
System.out.println("Successfull");
  }catch (Exception e){System.err.println("Error: " + e.getMessage());}
  }//main
}//class
-----------------------------------------------------------------------------------------------------------

Create File Using Java

Some times we need to create a File,using java.Here is the code


CreateFile.java
----------------------------------------------------------------------------------------------------
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class CreateFile
{
    public static void main(String[] args) throws IOException
    {
        boolean msg=false;
        File f = new File("c:/myfile.txt");
        //check if file is not present
        if (!f.exists()) msg=f.createNewFile();//returns boolean
       
        System.out.println("File Created ?"+msg);
       
        FileWriter fstream = new FileWriter("c:/myfile.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        out.write("Hello World2");
        out.close();
        System.out.println("File Written Successfully");
    }
}
-----------------------------------------------------------------------------------------------

Saturday, November 26, 2011

Suns secret WebServer from java6 onwards

Sun Ms has given its own HttpWebServer,using which you can even create a simple webServer like Tomcat.
com.sun.net.httpserver.HttpServer is a class representing WebServer.
You can find this class inside java\jre 1.6.0\lib\rt.jar