0

我在我的应用程序中遇到了一个问题。我有一个文本文件,其中包含一段代码,我需要检索它以应用于一个字符串变量。问题是哪种方法最好?我在下面运行了这些示例,但它们在逻辑上不正确/不完整。看一看:

  1. 通读:

    BufferedReader bfr = new BufferedReader(new FileReader(Node));
    
    String line = null;
    try {
        while( (line = bfr.readLine()) != null ){
            line.contentEquals("d.href");
            System.out.println(line);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
  2. 通读字符:

    BufferedReader bfr = new BufferedReader(new FileReader(Node));
    int i = 0;
    try {
        while ((i = bfr.read()) != -1) {
             char ch = (char) i;
             System.out.println(Character.toString(ch));
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    };
    
  3. 通过扫描仪阅读:

    BufferedReader bfr = new BufferedReader(new FileReader(Node));
    BufferedReader bfr = new BufferedReader(new FileReader(Node));
    int wordCount = 0, totalcount = 0;
    Scanner s = new Scanner(googleNode);
    while (s.hasNext()) {
       totalcount++;
       if (s.next().contains("(?=d.href).*?(}=?)")) wordCount++;
    }
    System.out.println(wordCount+" "+totalcount);
    

使用 (1.) 我很难找到d.href包含代码片段的开头。
使用(2.)我想不出或找到一种方法来存储d.href为字符串并检索其余信息。
使用 (3.) 我可以正确找到d.href但我无法检索 txt 的片段。

有人可以帮我吗?

4

2 回答 2

1

作为我的问题的答案,我使用扫描仪逐字阅读文本文件中的内容。.contains("window.maybeRedirectForGBV")返回一个布尔值和hasNext()一个字符串。然后,我在我想要的前一个单词停止了对文本文件上的代码拉伸的查询,并再向前移动一次以将下一个单词的值存储在一个字符串变量上。从这一点开始,您只需要按照您想要的方式处理您的字符串。希望这有帮助。

String stringSplit = null;
           Scanner s = new Scanner(Node);
           while (s.hasNext()) {

            if (s.next().contains("window.maybeRedirectForGBV")){
                stringSplit = s.next();
                break;
            }
           }
于 2013-07-24T21:33:37.173 回答
0

您可以像这样使用正则表达式:

Pattern pattern = Pattern.compile("^\\s*d\\.href([^=]*)=(.*)$");
// Groups:                                      1-----1 2--2
// Possibly spaces, "d.href", any characters not '=', the '=', any chars.

....
    Matcher m = pattern.matcher(line);
    if (m.matches()) {
        String dHrefSuffix = m.group(1);
        String value = m.group(2);
        System.out.println(value);
        break;
    }

BufferedReader 会做。

于 2013-07-24T16:53:37.710 回答