Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Tuesday, May 5, 2015

Regular Expression Powerfull sample in java

 We can use regular expression and to do large set of works as simple and single line code .

In this example i will show you how the regular expression play a vital stage .
I want to read a file and insert a new line (\n) at every 100 th character in that file content and write those changes in another file.

Normally what i did first is written a code to read file line by line and written a sample piece of code to read position and insert the new line in that particular position then written in new file.

Instead for write separate function i write an replaceAll with regular expression.

The sample code given below,


package com.shinnedhawks;

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

public class REPower {
    public static void main(String[] args) {
        new REPower().replace();
    }

    public void replace() {
        String oldFileName = "abc.txt";
        String tmpFileName = "abcnew.txt";

        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            br = new BufferedReader(new FileReader(oldFileName));
            bw = new BufferedWriter(new FileWriter(tmpFileName));
            String line;
            while ((line = br.readLine()) != null) {
                line = line.replaceAll("(.{100})", "$1\n"); // Here is the code it simplefied that largest code in single
                bw.write(line);
            }
        } catch (Exception e) {
            return;
        } finally {
            try {
                if(br != null)
                    br.close();
            } catch (IOException e) {
                // handle code
            }
            try {
                if(bw != null)
                    bw.close();
            } catch (IOException e) {
                // handle code
            }
        }
        // Once everything is complete, delete old file..
        File oldFile = new File(oldFileName);
        oldFile.delete();

        // And rename tmp file's name to old file name
        File newFile = new File(tmpFileName);
        newFile.renameTo(oldFile);

    }
}

No comments:

Post a Comment