bufferedreader搜索文本文件?

时间:2015-08-30 09:33:33

标签: java

file txt:

  

1 aaa 100

其中insert number为输出null

java:

private static void SearchForId() {
        try {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Inter Id");
            String id = scanner.next();
            BufferedReader Buffer = new BufferedReader(new FileReader(new File(
                    "D://Save.txt")));
            String line = null;
            while ((line = Buffer.readLine()) != null) {
                if (line.trim().equals(id)) {
                    System.out.println(line + "\n");

                }

            }
        } catch (Exception e) {
            System.out.print("" + e);
        }

    }

问题出在哪里。??

2 个答案:

答案 0 :(得分:0)

你可以这样试试。

    private static void SearchForId() {
    try {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Inter Id");
        String id = scanner.next();
        BufferedReader Buffer = new BufferedReader(new FileReader(new File(
                "D://Save.txt")));
        String line = null;
        while ((line = Buffer.readLine()) != null) {
            String arr[] = line.split(" ");
            for (int i = 0; i < arr.length; i++) {
                if (arr[i].trim().equals(id)) {
                    System.out.println(line);

                }
            }

        }
    } catch (Exception e) {
        System.out.print("" + e);
    }

答案 1 :(得分:-1)

如果我正确理解了这个问题,那么您在这里不需要Scanner

private static void SearchForId() {
    try {
        System.out.println("Inter Id");
        BufferedReader Buffer = new BufferedReader(new FileReader(new File(
                "D://Save.txt")));
        String[] line = Buffer.readLine().split(" ");
        int a = Integer.parseInt(line[0]);
        String s = line[1];
        int b = Integer.parseInt(line[2]);
    } catch (Exception e) {
        System.out.print("" + e);
    }

}