"Before software can be reusable it first has to be usable"- Ralph Johnson

Friday, September 23, 2011

Simple Word Replacement From A String Using Regular Expression

By 1:37 AM
Here is a class which replace some words from a given string using Regular Expression.
/*
 * This code writes "One dog, two dogs in the yard."
 * to the standard-output stream:
 */
import java.util.regex.*;

public class Replacement {
    public static void main(String[] args) 
                         throws Exception {
        // Create a pattern to match cat
        Pattern p = Pattern.compile("cat");
        // Create a matcher with an input string
        Matcher m = p.matcher("one cat," +
                       " two cats in the yard");
        StringBuffer sb = new StringBuffer();
        boolean result = m.find();
        // Loop through and create a new String 
        // with the replacements
        while(result) {
            m.appendReplacement(sb, "dog");
            result = m.find();
        }
        // Add the last segment of input to 
        // the new String
        m.appendTail(sb);
        System.out.println(sb.toString());
    }
}
Read More...

Search For Any Comment Line in a .java File Using Regular Expression

By 12:24 AM
The following class searches for the line which are being commented in a file called "Test.java".
 /*
 * Prints out the comments found in a .java file.
 */
import java.util.regex.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;

public class CharBufferExample {
    public static void main(String[] args) throws Exception {
        // Create a pattern to match comments
        Pattern p = 
            Pattern.compile("//.*$", Pattern.MULTILINE);
        
        // Get a Channel for the source file
        File f = new File("Test.java");
        FileInputStream fis = new FileInputStream(f);
        FileChannel fc = fis.getChannel();
        
        // Get a CharBuffer from the source file
        ByteBuffer bb = 
            fc.map(FileChannel.MAP_RO, 0, (int)fc.size());
        Charset cs = Charset.forName("8859_1");
        CharsetDecoder cd = cs.newDecoder();
        CharBuffer cb = cd.decode(bb);
        
        // Run some matches
        Matcher m = p.matcher(cb);
        while (m.find())
            System.out.println("Found comment: "+m.group());
    }
}

Read More...

Removing Control Characters from a File Using Regular Expression

By 12:17 AM
Here we have a sample class which will remove all the control characters from a file. 
/* This class removes control characters from a named
*  file.
*/
import java.util.regex.*;
import java.io.*;

public class Control {
    public static void main(String[] args) 
                                 throws Exception {
                                 
        //Create a file object with the file name
        //in the argument:
        File fin = new File("fileName1");
        File fout = new File("fileName2");
        //Open and input and output stream
        FileInputStream fis = 
                          new FileInputStream(fin);
        FileOutputStream fos = 
                        new FileOutputStream(fout);

        BufferedReader in = new BufferedReader(
                       new InputStreamReader(fis));
        BufferedWriter out = new BufferedWriter(
                      new OutputStreamWriter(fos));

	// The pattern matches control characters
        Pattern p = Pattern.compile("{cntrl}");
        Matcher m = p.matcher("");
        String aLine = null;
        while((aLine = in.readLine()) != null) {
            m.reset(aLine);
            //Replaces control characters with an empty
            //string.
            String result = m.replaceAll("");
            out.write(result);
            out.newLine();
        }
        in.close();
        out.close();
    }
}
Read More...

Usage of "Final" keyword in Java

By 12:11 AM
No matter how  often we use final keyword in our Java program, but we should use the final keyword liberally to communicate our intent.

The final keyword has more than one meaning :
  • A final class cannot be extended.
  • A final method cannot be overridden.
  • A final field, parameter and local variable cannot change their value once set.
In the last case, "value" for primitives is understood in the usual sense, while "value" for objects means the object's identity, not its state. Once the identity of a final object reference is set, it can still change its state, but not its identity.

Declaring primitive fields as final automatically ensures thread-safety for that field.
Some habitually declare parameters as final, since this almost always the desired behaviour. Others find this verbose, and of little real benefit.

Consistently using final with local variables (when appropriate) can be useful as well. It brings attention to the non-final local variables, which usually have more logic associated with them (e.g:- result variables, accumulators, loop variables). Many find this verbose. A reasonable approach is to use final for local variables only if there is at least one non-final local variable in the method ; this serves to quickly distinguish the non-final local variables from the others.

So here have the advantages of using final :
  • Clearly communicates your intent
  • Allows the compiler and virtual machine to perform minor optimizations
  • Clearly flags items which are simpler in behavior - final says,  "If you are looking for complexity, you won't find it here."
Read More...

Sunday, September 18, 2011

Simplest Way To Connect To A Shared Folder in Windows With Java

By 10:08 AM
Sometimes we usually meet a situation like, we want to access a shared folder in windows environment remotely. So this is one of the simplest way to do so :-
    File file = new File("\\\\theRemoteIP\\webapps"); 
    File[] files = file.listFiles();  
    System.out.println("Access granted");  

    for (int i = 0; i < files.length; i++)  
    {  
        String fname = files[i].getName();  
        System.out.println(fname);  
    }
Read More...

Saturday, September 10, 2011

New Features Of JDK 7

By 2:53 AM


With JDK 7 out the door, many writeups of the release have naturally focused on its larger features like Project Coin, NIO.2, the fork/join framework, and invokedynamic. However, there are a number of small but useful library conveniences in JDK 7 that shouldn't be overlooked.
  • To allow more informative assertion errors to be constructed, AssertionError now includes a constructor taking a string message and a Throwable cause, which is one of the four conventional constructors for exception types.
  • The methods which convert strings to numeric values differed in whether or not a leading plus, "+", was regarded as valid input. Float, Double, and BigDecimal accepted a leading plus while Byte, Short, Integer, Long, and BigInteger did not. As of JDK 7, all those types consistently accept a leading plus in their parseFoo, valueOf, and decode methods.
  • To help write more efficient comparators, Boolean, Byte, Character, Short, Integer, and Long each have a two-argument static compare method that performs the desired comparison operation without boxing overhead.
  • This six checked exception types that can be thrown by core reflection now have a common supertype, ReflectiveOperationException. This additional type complements the improved exception handling available with multi-catch and more precise re-throw from Project Coin.
  • The java.util.Objects class contains a number of small, but commonly used methods, many of them for coping with null inputs. For example, Objects contains a two-argument static equals method which does the right thing on null inputs. I've replaced a half-dozen copies of that method's logic in the JDK; I'm sure many more instances can be removed in other code bases as JDK 7 is adopted.
  • Part of NIO.2, I expect over time the utility methods in java.nio.file.Files to copy, read, and write the contents of file will see heavy usage.
And To recall, these are the list of feature which we discussed :-

  • Modularity
  • Multi-Language Support
  • New Garbage Collector
  • NIO.2 New File System API
  • Additional Swing API
Read More...