Thursday 29 May 2014

Update specific lines in a file using Java 1.7 >

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * This class creates the correction  file from the original  file.
 * This class performs the following tasks.
 *
 * 1) Convert the original  files to correction files. The input for the class are the original  files, which is
 *    test_file.txt
 * 2) Creates the correction files namely, test_file_correction.txt
 * 3) The difference between the original  file and the correction  file are as follows
 * a) if the source reference is XYZ, then it would be replaced with XYZ/AMENDED and
 * respective name space would be replaced with original name appended with "_correction"
 * b) Similar to above, O_XYZ will be changed to O_XYZ/AMENDED
 *
 * @author ppillai
 *
 */

public class SourceGenerator {

public static void main(String[] args)  {
        List lines = null;
       String sourceFileName1 = "dev\\xyz\\test_file.txt";
        String targetFileName1 = "dev\\xyz\\test_filecorrection.txt";
        String targetFileName = null;
        ArrayList listOfFiles = new ArrayList();
        listOfFiles.add(sourceFileName1);
        listOfFiles.add(sourceFileName2);
        int count = 0;
        for (String sourceFileName : listOfFiles)
        {
       lines = readFile(sourceFileName);
       targetFileName = targetFileName1;
       try (PrintWriter pw = new PrintWriter(new FileWriter(targetFileName)))
       {
       for(String line: lines)
       {
        line = processLines(line);
        if (line != null)
        pw.println(line);
       }
       pw.close();
       count+=1;
       }
       catch (IOException ioe) {
           ioe.printStackTrace();
       }
        }
}
private static List readFile(String FileName) {
Path FilePath = Paths.get(FileName);
        try (BufferedReader fileReader = Files.newBufferedReader(FilePath, Charset.defaultCharset())) {
            List lines = new ArrayList<>();
            String line = null;
            while ((line = fileReader.readLine()) != null )
                lines.add(line);
            return lines;
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }      
        return null;
    }
private static String processLines(String line)
{

if (!line.contains("_notification"))
{
if (line.contains("\"XYZ\""))
{
line = line.replaceAll("\"XYZ\"",XYZ_NEW);
line = line.replaceAll("Tag:XYZ","Tag:"+XYZ_PENDING);
}
if (line.contains("\"O_XYZ\""))
{
line = line.replaceAll("\"O_XYZ"","O_XYZ/AMENDED");
line = line.replaceAll("Tag:O_XYZ","Tag:"+"O_XYZ/AMENDED");
}

}
return line;
}
}

No comments: