Tuesday, June 11, 2013

How to read, write, delete, update file content using Java

How to read, write, delete, update file content using Java


package com.fm.helloworld.customer.model.fileutil;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;

public class FileUtil {
    public FileUtil() {
        super();
      int a=34;
      Integer a1 = new Integer("34");
      System.out.println(a1);
    }

    /**
     * This method reads the contents of the given file
     * and returns the String
     * @param fileName
     * @return
     */
    public String readFileContent(String fileName) {
        StringBuilder sb = new StringBuilder();
        // Get the reference of given File
        File file = new File(fileName);
        int ch;
        // FileInputStream variable
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
            // Iterate through every character of given File
            while ((ch = fin.read()) != -1)
                sb.append((char)ch);
            fin.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        return sb.toString();
    }

    /**
     * This method creates a new File
     * @param fileName
     * @param fileContent
     * @return
     */
    public boolean createFile(String fileName, String fileContent) {
        boolean isSuccess = true;
        try {
            File f1 = new File(fileName);
            BufferedWriter bw = new BufferedWriter(new FileWriter(f1));
            bw.write(fileContent);
            bw.close();
        } catch (Exception e) {
            System.out.println(e);
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     * This method reads the contents of the given file using Buffer Reader
     * and returns the String
     * @param fileName
     * @return
     */
    public String readFileContentUsingBufferReader(String fileName) {
        StringBuilder sb = new StringBuilder();
        // Get the reference of given File
        File file = new File(fileName);
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            while (true) {
                String str = br.readLine();
                if (str == null) {
                    break;
                } else {
                    sb.append(str);
                }
            }
            br.close();
        } catch (Exception e) {
            System.out.println(e);
        }
        return sb.toString();
    }
    /**
     * This method updated the given file with given content.
     * If everything goes fine, return true otherwise return false
     * @param fileName
     * @param fileContent
     * @return
     */
    public boolean updateFile(String fileName, String fileContent) {
        boolean isSuccess = true;
        StringBuilder sb = new StringBuilder();
        try {
            File f1 = new File(fileName);
            if (f1.canWrite()) {
                String existFileContent =
                    readFileContentUsingBufferReader(fileName);
                sb.append(existFileContent);
                BufferedWriter bw = new BufferedWriter(new FileWriter(f1));
                sb.append(fileContent);
                bw.write(sb.toString());
                bw.close();
            }

        } catch (Exception e) {
            System.out.println(e);
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     * This file copies data from srcFile to tgtFile
     * @param srcFile
     * @param tgtFile
     * @return
     */
    public boolean copyFile(String srcFile, String tgtFile) {
        boolean isSuccess = true;
        try {
            String existFileContent =
                readFileContentUsingBufferReader(srcFile);
            createFile(tgtFile, existFileContent);

        } catch (Exception e) {
            System.out.println(e);
            isSuccess = false;
        }
        return isSuccess;
    }

    /**
     *
     * @param fileName
     * @return
     */
    public boolean updateFileStatus(String fileName,boolean isReadOnly) {
        boolean isSuccess = true;
        StringBuilder sb = new StringBuilder();
        try {
            File file = new File(fileName);

            if(isReadOnly){
                file.setReadOnly();
            }else{
                file.setWritable(true);
            }
           
            boolean readOnly = file.canWrite();
            System.out.println("File Status : " + readOnly);

        } catch (Exception e) {
            System.out.println(e);
            isSuccess = false;
        }
        return isSuccess;
    }
    /**
     *
     * @param dirName
     * @return
     */
    public boolean createDirectory(String dirName){
        boolean isSuccess = true;
       
        try {
            File file = new File(dirName);
            file.mkdirs();

        } catch (Exception e) {
            System.out.println(e);
            isSuccess = false;
        }
        return isSuccess;
    }
    public static void main(String[] args) {
        FileUtil util = new FileUtil();
        //String fileContent=util.readFileContent("C:/RKP/emp.txt");
        //System.out.println(fileContent);
        String fileName = "C:/RKP/fmtest.txt";
        String tgtFileName = "C:/RKP/fmtest_copy.txt";
        String fileContent = null;
        boolean isSuccess = false;
        fileContent = " || Fortune Minds Inc - April 23";
        String dirName="C:/tmp/tmp1";
       
        //isSuccess= util.createDirectory(dirName);
         //isSuccess = util.createFile(fileName, fileContent);
        //fileContent = util.readFileContentUsingBufferReader(fileName);
        //isSuccess = util.updateFileStatus(fileName,true);
        //isSuccess = util.updateFile(fileName, fileContent);
        //isSuccess = util.updateFileStatus(fileName, false);
        //isSuccess = util.updateFile(fileName, fileContent);
        isSuccess=util.copyFile(fileName, tgtFileName);
        System.out.println(isSuccess);
        System.out.println(fileContent);
    }
}

Monday, June 3, 2013

How to get the logged in Host & User Details in Java

How to get the logged in Host Name & User Details in Java?

import java.net.InetAddress;

 String hostName = InetAddress.getLocalHost().getHostName();

To get logged in user name

String user = System.getProperty("user.name");

Friday, May 31, 2013

Date Conversions using XMLGregorianCalendar in Java

How to convert to different date data types using XMLGregorianCalendar in Java


/**
   * Returns XMLGregorianCalendar for Current Date and Time.
   */
  public XMLGregorianCalendar getCurrentDateTimeAsXMLGregorianCalendar()
  {
    GregorianCalendar gc = new GregorianCalendar();
    return new XMLGregorianCalendarImpl(gc);
  }

  /**
   * Convert supplied XMLGregorianCalendar to java util Date
   */
  public Date getJavaDateFromXMLGregorianCal(XMLGregorianCalendar pXCal)
  {
    if (pXCal != null)
    {
      return pXCal.toGregorianCalendar().getTime();
    }
    return null;
  }
   // Convert java.util.Date to XMLGregorianCalendar
  public XMLGregorianCalendar toXMLGregorianCalendar(Date pDate)
  {
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTimeInMillis(pDate.getTime());
    return new XMLGregorianCalendarImpl(gc);
  }

Tuesday, May 28, 2013

How to retrieve data from Oracle Database using JSP

How to connect to Oracle Database in JSP ? How to query & Retrieve data from Database in JSP

- Below is the snippet about connecting to Oracle Database in JSP



Below is the snapshot to retrieve data from Result set and display it on to the screen using JSTL tab libraries in JSP


Thursday, May 23, 2013

How to Write JUnit Tests using Jdeveloper

JUnit is a simple, open source framework to write and run repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. JUnit features include:
- Assertions for testing expected results
- Test fixtures for sharing common test data
- Test runners for running tests
File -> New -> Choose TestSuite as shown below




- Create a Test class as shown below


- Write the test methods as shown below, Ensure to have @Test annotation.
- Ensure to import below packages
                      import static org.junit.Assert.*;
                      import org.junit.Test;


- Open the test suite class, Structure Window -> Right click on class name -> Choose Run/Debug option



- Once you run all the tests, below is the screenshot how it looks like the results.

For More Info, visit : http://junit.sourceforge.net/doc/faq/faq.htm#running_15

Tuesday, May 7, 2013

Remote Desktop Share using Google Chrome browser

Google chrome has one of the best feature, I use frequently. i.e Remote Desktop Sharing. Very simple to access remote desktop.


Step1 : Open the below url in Google Chrome browser

https://chrome.google.com/webstore/detail/chrome-remote-desktop/gbchcmhmhahfdphkhkmpfmihenigjmpp/related

Step2 :  Click on 'Launch App' button

Step 3:  If you want to access remote machine, then click on 'Access' , Get the access code from other end , enter the access code when prompted, you are all set to access the remote machine.

Step4 : If someone want to access your machine, then click on 'Share' , Provide the generated access code to other end, The should able to access your machine.


Wednesday, May 1, 2013

How to convert Array to List and List to Array

Use case : How to convert java.util.List to Array & Array to java.util.List in Java

Implementation : 

List to Array conversion

List<String> nameList = new ArrayList<String>();
nameList.add("Steve");
nameList.add("Tom");

// Convert List to Array with Generics.
String[] nameArray = nameList.toArray(new String[nameList.size()]);

Array to List conversion

// Convert Arrays to List with Generics
List<String> lastNameList = new ArrayList<String>(Arrays.asList(nameArr));