【问题标题】:Java extract text from text file from a certain point on the textJava从文本文件中的某个点提取文本
【发布时间】:2015-07-29 16:24:44
【问题描述】:

我使用BufferedReader 创建了一个方法,该方法可以打开程序先前创建的文本文件并提取一些字符。我的问题是它提取了整行,我只想在指定字符 : 之后提取。

这是我的try/catch 块:

try {
    InputStream ips = new FileInputStream("file.txt"); 
    InputStreamReader ipsr = new InputStreamReader(ips); 
    BufferedReader br1 = new BufferedReader(ipsr); 

    String ligne;
        while((ligne = br1.readLine()) != null) {
            if(ligne.startsWith("Identifiant: ")) {
                System.out.println(ligne);
                id = ligne;
            }
            if(ligne.startsWith("Pass: ")) {
                System.out.println(ligne);
                pass = ligne;
            }
        }
        System.out.println(ligne);
        System.out.println(id);
        System.out.println(pass);
        br1.close();
    } catch (Exception ex) {
        System.err.println("Error. "+ex.getMessage());
    }

目前,我返回我的String id 整个ligne,pass 也是如此——顺便说一句,所有sysout 都是测试,在那里毫无用处。

如果有人知道如何将: 之后的行而不是整行发送到 id,我可能搜索不好,但 google 不是我的朋友。

【问题讨论】:

    标签: java filter inputstream bufferedreader inputstreamreader


    【解决方案1】:

    你为什么不尝试在ligne 上做一个split()?

    如果您使用String[] splittedLigne = ligne.split(":");,您将在splittedLigne 中拥有以下内容:

    splittedLigne[0] -> :之前是什么

    splittedLigne[1] -> :之后是什么

    这将为您提供每一行所需的内容。此外,如果您有多个 :,这也适用于您。

    【讨论】:

    • 分割方法,谢谢你的回答,我也试试:) 如果它比une :per line 更有效。
    【解决方案2】:

    使用 StringUtils

    StringUtils.substringAfter(id ,":"),

    【讨论】:

      【解决方案3】:

      假设字符串中只有一个 : 符号,您可以使用

       id = ligne.substring(ligne.lastIndexOf(':') + 1);
      

      【讨论】:

      • 每行确实只有一个:,效果很好。感谢您的回答,我发现了substring方法,非常强大。
      • 或id = id.substring(id.indexOf(':') + 1);,如果你想在第一个:之后开始...
      • 我刚刚编辑了我的答案,你应该从 ligne 而不是 id 子串,对不起。
      • Stugal 的错误没问题,我将您的答案改编为我的代码,如下所示:pass = ligne.substring(ligne.lastIndexOf(':')+2); :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多