使用java扫描仪解析文本文件

使用java扫描仪解析文本文件,java,java.util.scanner,bots,Java,Java.util.scanner,Bots,我正在尝试创建一个方法来解析文本文件并返回一个字符串,该字符串是冒号后面的url。文本文件如下所示(适用于机器人): 关键词:url 关键词,关键词:url 因此,每行由一个关键字和一个url组成,或者由多个关键字和一个url组成 谁能告诉我怎么做?多谢各位 我相信我需要使用扫描仪,但在任何人身上都找不到任何与我类似的东西 多谢各位 编辑:我尝试使用下面的建议。不太管用。任何帮助都将不胜感激 public static void main(String[] args) throws IO

我正在尝试创建一个方法来解析文本文件并返回一个字符串,该字符串是冒号后面的url。文本文件如下所示(适用于机器人):

关键词:url
关键词,关键词:url

因此,每行由一个关键字和一个url组成,或者由多个关键字和一个url组成

谁能告诉我怎么做?多谢各位

我相信我需要使用扫描仪,但在任何人身上都找不到任何与我类似的东西

多谢各位

编辑:我尝试使用下面的建议。不太管用。任何帮助都将不胜感激

    public static void main(String[] args) throws IOException {
    String sCurrentLine = "";
    String key = "hello";

    BufferedReader reader = new BufferedReader(
            new FileReader(("sites.txt")));
    Scanner s = new Scanner(sCurrentLine);
    while ((sCurrentLine = reader.readLine()) != null) {
        System.out.println(sCurrentLine);
        if(sCurrentLine.contains(key)){
            System.out.println(s.findInLine("http"));
        }
    }
}
输出:

    hello,there:http://www.facebook.com
null
whats,up:http:/google.com

sites.txt:

   hello,there:http://www.facebook.com
whats,up:http:/google.com


这应该会对您有所帮助。

使用BufferedReader,对于文本解析,您可以使用常规表达式

您应该使用拆分方法:

String strCollection[] = yourScannedStr.Split(":", 2);
String extractedUrl = strCollection[1];

您应该使用
BufferedReader
逐行读取文件,我建议您使用regex解析文件

模式


(?您看过扫描仪文档了吗?使用
BufferedReader
获取文件的行,然后您可以使用
扫描仪
拆分
或最简单的正则表达式标记行。
public static void main(String[] args) throws Exception {
    final String file = "hello,there:http://www.facebook.com\n"
            + "whats,up:http://google.com";
    final Pattern pattern = Pattern.compile("(?<=:)http://[^\\s]++");
    final Matcher m = pattern.matcher("");
    try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(file.getBytes("UTF-8"))))) {
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            m.reset(line);
            while (m.find()) {
                System.out.println(m.group());
            }
        }
    }
}