Samvid Kulkarni
Samvid Kulkarni

Reputation: 129

How to extract starting of a String in Java

I have a text file with more than 20,000 lines and i need to extract specific line from it. The output of this program is completely blank file.

There are 20,000 lines in the txt file and this ISDN line keeps on repeating lots of time each with different value. My text file contains following data.

RecordType=0(MOC) 
sequenceNumber=456456456
callingIMSI=73454353911
callingIMEI=85346344
callingNumber
AddInd=H45345'1
NumPlan=H34634'2
ISDN=94634564366 // Need to extract this "ISDN" line only

public String readTextFile(String fileName) {
    String returnValue = "";
    FileReader file = null;
    String line = "";
    String line2 = "";

    try {
        file = new FileReader(fileName);
        BufferedReader reader = new BufferedReader(file);
        while ((line = reader.readLine()) != null) {               
            // extract logic starts here
            if (line.startsWith("ISDN") == true) {
                System.out.println("hello");
                returnValue += line + "\n";
            }     
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException("File not found");
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return returnValue;
}

Upvotes: 0

Views: 68

Answers (1)

fge
fge

Reputation: 121710

We will assume that you use Java 7, since this is 2014.

Here is a method which will return a List<String> where each element is an ISDN:

private static final Pattern ISDN = Pattern.compile("ISDN=(.*)");

// ...

public List<String> getISDNsFromFile(final String fileName)
    throws IOException
{
    final Path path = Paths.get(fileName);
    final List<String> ret = new ArrayList<>();

    Matcher m;
    String line;

    try (
        final BufferedReader reader
            = Files.newBufferedReader(path, StandardCharsets.UTF_8);
    ) {
        while ((line = reader.readLine()) != null) {
            m = ISDN.matcher(line);
            if (m.matches())
                ret.add(m.group(1));
        }
    }

    return ret;
}

Upvotes: 2

Related Questions