jonny
jonny

Reputation: 177

how to extract dynamically populated alphanumeric word from pipe delimited file

I am trying to print (Sys.out) alphanumeric word that is dynamically populated in piped delimited file. So far i am able to read the file and also iterate through each word by character but i want to print this word as whole instead of printing it as a word by word in a line.

Below is my attempted code -

public void extract_id() {

    File file= new File("src/test/resources/file.txt");
    Scanner sc=null;
    String str=null;
    try {
        sc=new Scanner(file);

        while(sc.hasNextLine()){
            str=sc.nextLine();
            parseID(str);

        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    sc.close();
}

private void parseId(String str) {
    String printId;
    Scanner sc=new Scanner(str);
    sc.useDelimiter("|");

    while(sc.hasNext()){
        if(sc.next().contains("ID")){
            printId=sc.next();
            System.out.println("Id is "+printId);
        }       
    }
    sc.close();
}

My goal is to print - AF12345

Sample Delimited pipe file

id|1|session|26|zipCode|73112
id|2|session|27|recType|dummy
id|3|session|28|ID|AF12345|

Upvotes: 1

Views: 40

Answers (1)

Mick Mnemonic
Mick Mnemonic

Reputation: 7956

Your main problem is the delimiter string you're passing to Scanner.useDelimiter(). That method is expecting a regular expression and the pipe (|) character happens to be a reserved one in this context, which means that you need to escape it, i.e. call the method like this:

sc.useDelimiter("\\|");

However, you don't need to use another Scanner for parsing the Id from the line of text. String.split() is enough:

private void parseId(String str) {
    String[] tokens = str.split("\\|");

    for (int i = 0; i < tokens.length; i++) {
        if (tokens[i].equals("ID")) {
            String idValue = tokens[i + 1]; // this will throw an error if
                                            // there is nothing after ID on
                                            // the row
            System.out.println("Id is " + idValue);
            break;
        }
    }
}

Upvotes: 1

Related Questions