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

问题描述 投票:-1回答:1

我是java的新手,这可能听起来真的很愚蠢但是!假设你的电脑里有这个txt文件

The_txt.txt

安东尼

Anthony [email protected]

01234567891

地点


玛丽

[email protected]

1234561234

LOCATION2


乔治

[email protected]

1234512345

LOCATION3


我想用这个txt做的是,我提示用户插入一个电话号码,所以如果用户提供Maria的电话号码(1234561234),程序将输出

玛丽

[email protected]

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();
        }
    }

先感谢您!!!

java file for-loop
1个回答
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();
        }
      }
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.