Tuesday, December 11, 2012

Search String in text file and return line number.

Inputs:
searchString
fileName

outputs:
exists
lineNum
error

Code:
IDataCursor pipelineCursor = pipeline.getCursor();
        String    searchString = IDataUtil.getString( pipelineCursor, "searchString" );
        String    fileName = IDataUtil.getString( pipelineCursor, "fileName" );
        pipelineCursor.destroy();
        
        File file=new File(fileName);    
        int lineNum = 0;
        
        try {
            Scanner in = new Scanner(new FileReader(file));
            
            while (in.hasNext()) {
            String inString = in.nextLine().toLowerCase();
            if( inString.indexOf( searchString ) >= 0) 
            {             
                IDataUtil.put( pipelineCursor, "lineNum", Integer.toString(lineNum));
                IDataUtil.put( pipelineCursor, "exists", "true");
                break;
            }
            else{
                IDataUtil.put( pipelineCursor, "exists", "false");
            }
            lineNum++;
            }            
        } catch (FileNotFoundException e) {        
            IDataUtil.put( pipelineCursor, "error", e.toString());
        }
        pipelineCursor.destroy();
Imports:

Code:
import java.io.FileReader;
import java.util.Scanner;
import java.io.File;

No comments:

Post a Comment