Friday, May 13, 2016

Get the file Name from the Path using java.nio.file.Paths API



Code Snippet : 

import java.nio.file.Path;
import java.nio.file.Paths;


public class GetFileName {

       public static void main(String[] args) {
              String filePath = "MESSAGE_PATH";
              Path p = Paths.get(filePath);
              String fileName = p.getFileName().toString();
              int index = fileName.indexOf(".");
              String mainChapterNumber = fileName.substring(0,index);
              System.out.println(mainChapterNumber);
       }


}

Retrieve all Dependencies from the pom.xml


Code Snippet : 

package com.bnp.pomparser;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;

import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

public class ParseMe {

       public static void main(String[] args) throws IOException, XmlPullParserException {
         Reader reader = new FileReader("POM_XML_PATH");
         try {
           MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
           Model model = xpp3Reader.read(reader);
           List<Dependency> dependencyList = model.getDependencies();
           for(Dependency dependency : dependencyList){
             System.out.println("Group Id :: "+dependency.getGroupId());
             System.out.println("Artifact Id :: "+dependency.getArtifactId());
             System.out.println("Version Id :: "+dependency.getVersion());
           }
         } finally {
           reader.close();
         }
       }
}


Daylight Savings in Java : Find the Offset in GMT



The Code Snippet provides the Offset in GMT , When there is a 

Daylight savings for a respective time zone then the below code 

snippet provides the hours and minutes of how much the time 

should be offset in GMT Standard.

Code Snippet :

       public static String getCurrentTimezoneOffset(TimeZone timeZoneInstance) {
         Calendar _calenderInstance = GregorianCalendar.getInstance(timeZoneInstance);
         int offsetInMillis = timeZoneInstance.getOffset(_calenderInstance.getTimeInMillis());
         String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
         offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
         return "GMT"+offset;

       }

Transform Map to CSV (Comma Separated Values) Acceptable Acceptable String



Code Snippet :

       /**
        * Transform mapto string instances.
        *
        * @param propertymapperValues the propertymapper values
        * @return the string
        */
       private static String transformMaptoStringInstances(Map<String,String> propertymapperValues){
         StringBuilder _buildCSVContends = new StringBuilder();
         for(Entry<String,String> entryInstances : propertymapperValues.entrySet()){
           _buildCSVContends.append("\""+entryInstances.getKey()+"\"");
           _buildCSVContends.append(",");
           _buildCSVContends.append("\""+entryInstances.getValue()+"\"");
           _buildCSVContends.append("\n");
         }
         return _buildCSVContends.toString();
       }

Convert All data from Properties to a Hash Map In Java


Code Snippet :

/** The propertied values. */
       static Map<String,String> propertiedValues = new HashMap<String, String>();
       static{
         try {
              propertiedValues = getPropertiesAsMap(MESSAGE_PROPERTIES_PATH);
              System.out.println("The Size of the propertiedValues map is "+propertiedValues.size());
         } catch (FileNotFoundException fileNotFoundException) {
              fileNotFoundException.printStackTrace();
         } catch (IOException ioException) {
              ioException.printStackTrace();
         }
       }
      
       /**
        * Gets the properties as map.
        *
        * @param propertyFilePath the property file path
        * @return the properties as map
        * @throws FileNotFoundException the file not found exception
        * @throws IOException Signals that an I/O exception has occurred.
        */
       public static Map<String,String> getPropertiesAsMap(String propertyFilePath) throws FileNotFoundException, IOException{
         Properties properties = new Properties();
         Map<String,String> mapOfValues = new HashMap<String, String>();
         properties.load(new FileInputStream(propertyFilePath));
         for (String key : properties.stringPropertyNames()) {
           String value = properties.getProperty(key);
           mapOfValues.put(String.valueOf(key.trim()),value.trim());
         }
         return mapOfValues;
       }

Thursday, May 12, 2016

Get All Files from folder Including from Sub Folders In Java


Code Snippet :

       /**
        * Gets the all files from folder.
        *
        * @param directoryName the directory name
        * @param files the files
        * @return the all files from folder
        */
       public static void getAllFilesFromFolder(String directoryName, ArrayList<File> files) {
         File directory = new File(directoryName);
         File[] fList = directory.listFiles();
         for (File fileInstance : fList) {
           if (fileInstance.isFile() && fileInstance.getName().endsWith(".xhtml")) {
             files.add(fileInstance);
           } else if (fileInstance.isDirectory()) {
             getAllFilesFromFolder(fileInstance.getAbsolutePath(), files);
           }
         }
       }


The above code snippet gets all the files from the folders including the files in the sub folders and then check whether the file name ends with .xhtml and filters the files which are of Extension .xhtml.
Similarly users can filter the required file formats using the required file extensions

Write String in to CSV (Comma Separated Values) File in Java







Code Snippet :

       public static void writeStringAsCSV(String resultsetContentds,String filePath){
      FileOutputStream fileoutputStream = null;
         File fileInstance;
         try {
           fileInstance = new File(filePath);
              fileoutputStream = new FileOutputStream(fileInstance);
              if (!fileInstance.exists()) {
                fileInstance.createNewFile();
              }
              byte[] contentInBytes = resultsetContentds.getBytes();
              fileoutputStream.write(contentInBytes);
              fileoutputStream.flush();
              fileoutputStream.close();
         } catch (IOException exceptionTrace) {
           exceptionTrace.printStackTrace();
         } finally {
           try {
                if (fileoutputStream != null) {
                  fileoutputStream.close();
                }
              } catch (IOException exceptionTrace) {
                exceptionTrace.printStackTrace();
              }
         }

       }