如何在Java中提取String的起始 [英] How to extract starting of a String in Java

查看:113
本文介绍了如何在Java中提取String的起始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超过20,000行的文本文件,我需要从中提取特定行。该程序的输出完全是空白文件。

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.

txt文件中有20,000行,这条ISDN线路不断重复大量时间,每个都有不同的值。我的文本文件包含以下数据。

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;
}


推荐答案

我们假设您使用Java 7,因为这是2014年。

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

这是一个返回 List< String> 的方法element是一个ISDN:

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;
}

这篇关于如何在Java中提取String的起始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆