读取包含多个条目的文件,并根据用户输入输出一个条目

时间:2019-04-08 19:31:44

标签: java file for-loop

我是Java新手,这听起来确实很愚蠢,但是! 假设您的PC上某个位置有此txt文件

The_txt.txt

安东尼

anthonyk@somewhere.com

01234567891

位置


玛丽亚

maria@somewhere.com

1234561234

location2


乔治

george@somewhere.com

1234512345

location3


我要对此txt进行操作,我提示用户输入电话号码,因此,例如,如果用户提供了玛丽亚的电话号码(1234561234),程序将输出

玛丽亚

maria@somewhere.com

1234561234

location2

我完成此任务的代码:

    private static void Search_Contact_By_Phone(File file_location){

        Scanner To_Be_String = new Scanner(System.in);

        String To_Be_Searched = To_Be_String.nextLine();

        System.out.println("\n \n \n");

        BufferedReader Search_Phone_reader;
        try {
            Search_Phone_reader = new BufferedReader(new FileReader (file_location));
            String new_line = Search_Phone_reader.readLine();
            while (new_line != null) {
                if (To_Be_Searched.equals(new_line)){
                    for (int i=0;i<=3;i++){
                        System.out.println(new_line);
                        new_line = Search_Phone_reader.readLine();
                    }
                    break;
                }
                new_line = Search_Phone_reader.readLine();
            }
            Search_Phone_reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

预先感谢您!

1 个答案:

答案 0 :(得分:0)

package com.mycompany.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class Main {
  public static void main(String[] args) throws IOException {
    // For a small file
    Path path = Paths.get("The_txt.txt");
    String toBeSearched = "1234512345";
    List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
    // Better performance if i starts at 2 and i += 4
    for (int i = 0; i < lines.size(); i++) {
      if (lines.get(i).equals(toBeSearched)) {
        System.out.println(lines.get(i - 2));
        System.out.println(lines.get(i - 1));
        System.out.println(lines.get(i));
        System.out.println(lines.get(i + 1));
      }
    }
    // Else
    try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
      String line1;
      while ((line1 = reader.readLine()) != null) {
        String line2 = reader.readLine();
        String line3 = reader.readLine();
        if (line3.equals(toBeSearched)) {
          // Found
          System.out.println(line1);
          System.out.println(line2);
          System.out.println(line3);
          System.out.println(reader.readLine());
          break;
        } else {
          reader.readLine();
        }
      }
    }
  }
}