首页 > 解决方案 > 如何编写在文本文件中搜索字符串并在其后返回 int 值的方法?

问题描述

我需要的是在文本文件中搜索特定字符串并在此字符串之后返回 int 值的 Java 方法。如何将读取的行与文本文件分开。我的文本文件如下所示:

namea 80
nameb 50
namec 200
named 3400

文本文件应该有更多的行。

我的方法现在看起来像这样:

public int readfile(String searchedString, File txtfile){
int ret = 0;

        try {
        BufferedReader br = new BufferedReader(new FileReader(txtfile));

        String line = null;
        while ((line = br.readLine()) != null) {
            if (line.startsWith(searchedString + " ")) {
                
                ret = Integer.parseInt(//the number of the line);
            }
        }

        br.close();
        System.out.println(ret);

        } catch (IOException ex) {
          
        }
     return ret;

}

标签: javafiletext

解决方案


public int readfile(String searchedString, File txtfile){
int ret = 0;

        try {
        BufferedReader br = new BufferedReader(new FileReader(txtfile));

        String line = null;
        while ((line = br.readLine()) != null) {
            if (line.startsWith(searchedString + " ")) {
                String[] strArr = line.split(" ");
                int item = strArr.length - 1;
                ret = Integer.parseInt(strArr[item]);
            }
        }

        br.close();
        System.out.println(ret);

        } catch (IOException ex) {
           //handle it
        }
     return ret;
}

推荐阅读