Wednesday, May 9, 2012

How to write content into file in Java using BufferedWriter with example

How to write content into file in Java using BufferedWriter with example 

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

public class WriteFileExampleUsingBufferedWriter
{
  public static void main( String[] args )
    { 
      try
      {
       String fileContent = "Content Added  on "+new Date();
          File file = new File("d:\\db\\fileTest\\newfile.txt");
  
        //first check if the file is already there, if no file found then create new file
    if (!file.exists()) 
    {
     file.createNewFile();
     System.out.println("File Created Succefssfully");
    }
  
          FileWriter fw = new FileWriter(file.getName());
          BufferedWriter bw = new BufferedWriter(fw);
          bw.write(fileContent);
          bw.close();
  
          System.out.println("Content written Succefssfully");
      }
      catch(IOException e)
      {
       e.printStackTrace();
      }
     }
}

How to write content into file in Java using FileOutputStream with example

Here is the example to write content into file using FileOutputStream in Java

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
 
public class WriteFileExampleUsingFileOutputStream
{
 public static void main(String[] args)
 {
  FileOutputStream fos = null;
  File file;
  String fileContent = "Content Added  on "+new Date();
  try 
  {
   file = new File("d:\\db\\fileTest\\newfile.txt");
   fos = new FileOutputStream(file);
 
   //first check if the file is already there, if no file found then create new file
   if (!file.exists()) 
   {
    file.createNewFile();
    System.out.println("File Created Succefssfully");
   }
    // get the content in bytes
   byte[] contentInBytes = fileContent.getBytes();
 
   fos.write(contentInBytes);
   fos.flush();
   fos.close();
 
   System.out.println("Content written Succefssfully");
  } 
  catch (IOException e) 
  {
   e.printStackTrace();
  } 
  finally 
  {
   try
   {
    if (fos != null)
    {
     fos.close();
    }
   } 
   catch (IOException e) 
   {
    e.printStackTrace();
   }
  }
 }
}

How to read file in Java using BufferedReadetr with example

Example to demonstrate how to read a file in Java using BufferedReader classes with example. THis is most simple way to read file in java.
In this example readLine() method is used to read each line from file.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample1 
{
 public static void main(String[] args)
 {
  BufferedReader br = null;
  try 
  {
   String thisLise;
   br = new BufferedReader(new FileReader("D:\\db\\fileTest\\file1.txt"));
   while ((thisLise = br.readLine()) != null) 
   {
    System.out.println(thisLise);
   }
  } 
  catch (IOException e)
  {
   e.printStackTrace();
  }
  finally //finally closing the objects
  {
   try
   {
    if (br != null)br.close();
   } 
   catch (IOException ex)
   {
    ex.printStackTrace();
   }
  }
 }
}

How to read file in Java using BufferedInputStream with example

Example to demonstrate how to read a file in Java using BufferedInputStream and DataInputStream classes with example.
In this example readLine() method is used to read each line from file.


import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadFileExample
{
    public static void main(String[] args)
    {
        File file = new File("D:\\db\\fileTest\\file1.txt");
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        DataInputStream dis = null;

        try 
        {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            dis = new DataInputStream(bis);

            while (dis.available() != 0)
            {
                String lineString=dis.readLine();
                System.out.println(lineString);
            }
         } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally //finally closing file
        {
            try 
            {
                fis.close();
                bis.close();
                dis.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }
}

Create New File Example in Java

Java has provided java.io.file pacakge  to work with File.

To create a new file File.createNewFile( ) method is used.
This method returns a boolean value true if the file is created otherwise return false. If the mentioned file for the specified directory is already exist then the createNewFile() method returns the false otherwise the method creates the mentioned file and return true.
here is the example of creating New file in java 

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

public class CreateNewFileExample 
{
 public static void main(String[] args) 
 {
  new CreateNewFileExample().createFile();
 }
 public void createFile()
 {
  try {
    
        File file = new File("d:\\db\\fileTest\\newfile.txt");
  
        if (file.createNewFile())
        {
         System.out.println("File is created successfully!");
        }
        else
        {
         System.out.println("Cannot create file, file already exists.");
        }
      } 
  catch (IOException e)
  {
        e.printStackTrace();
  }
 }
}

Monday, May 7, 2012

Simple java clock in java applet using Thread


Below code is the example of Thread in Java. This is simple Java Applet to display clock using Java Thead.

import java.awt.*;
import java.applet.*;
import java.applet.*;
import java.awt.*;
import java.util.*;

public class ClockApplet extends Applet implements Runnable
{
   Thread t,t1;
   public void start(){
      t = new Thread(this);
      t.start();
   }
    public void run(){
      t1 = Thread.currentThread();
      while(t1 == t){
         repaint();
         try{
            t1.sleep(1000);   
         }
         catch(InterruptedException e){}
      }
   }

   public void paint(Graphics g){

      Calendar cal = new GregorianCalendar();

      String hour = String.valueOf(cal.get(Calendar.HOUR));

      String minute = String.valueOf(cal.get(Calendar.MINUTE));

      String second = String.valueOf(cal.get(Calendar.SECOND));

      g.drawString(hour + ":" + minute + ":" + second, 20, 30);

   }

}


Monday, April 30, 2012

How to run sonar for non-Maven based java project


 
To run sonar report, first we have to install maven & sonar in our local machine.For Non maven based project also we require maven because sonar require maven.
  1. Download and extract Maven in your C drive from http://www.apache.org/dyn/closer.cgi/maven/binaries/apache-maven-3.0.4-bin.zip
  2. Install Jdk 
  3. Download and extract Sonar in your D drive from http://dist.sonar.codehaus.org/sonar-3.0.zip
  4. Now go to D:\sonar-3.0\bin\windows-x86-32 and double click on StartSonar.batNow sonar server will start locally on http://localhost:9000
  5. Here maven require pom.xml for the project for which sonar report is to be generated, but non maven based project will not have any pom.xml.
    but we have to create a pom.xml in its project's parent folder as below.
  6.        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>[YOUR.ORGANIZATION]</groupId>
      <artifactId>[YOUR.PROJECT]</artifactId>
      <name>[YOUR PROJECT NAME]</name>
      <version>[YOUR PROJECT VERSION]</version>
      <build>
            <sourceDirectory>[YOUR SOURCE DIRECTORY]</sourceDirectory>
            <outputDirectory>[YOUR CLASSES/BIN DIRECTORY</outputDirectory>
            <plugins>
               <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <configuration>
                      <source>1.5</source>
                      <target>1.5</target>
                      <excludes>
                          <exclude>**/*.*</exclude>
                      </excludes>
                  </configuration>
               </plugin>
            </plugins>
      </build>
      <properties>
        <sonar.dynamicAnalysis>false</sonar.dynamicAnalysis>
      </properties>
    </project>
  7. Replace the parameters :

    Description Example
    [YOUR.ORGANIZATION] the id of your organization (no space) com.myorganization
    [YOUR.PROJECT] the id of your project (no space) my.project
    [YOUR PROJECT NAME] the name displayed into sonar (spaces allowed) My Project
    [YOUR PROJECT VERSION] the version. Set 1.0 if no specific version. 1.0
    [YOUR SOURCE DIRECTORY] the relative path to the sources directory src/java
    [YOUR CLASSES/BIN DIRECTORY] the relative path to the compiled java classes directory bin
  8.   

    Go to parent folder of your project, and run following command
    mvn sonar:sonar
  9. After its completion, browse http://localhost:9000/ where you will see the project list with code quality report as below