使用扫描仪在 ArrayList 上搜索内容并打印行

With a scanner search on ArrayList the content and print the line

我有一个文本文件 (.txt),但我被困在这里。 我使用 BufferReader 读取所有文件并保存在 ArrayList 中,然后将 ArrayList 放入 String 中以删除 , [ ] 现在我需要在用户想要的 ArrayList 中找到扫描仪 ex: (1001) 的词,并打印这个词所在的行和之后的 4 行。之后,编辑这 4 行并将 ArrayList 保存到文件中。

或者不使用 ArrayLists 有更简单的东西? 谢谢。

System.out.println("Digite o ID ou 1 para sair: ");
                Scanner sOPFicheiro = new Scanner(System.in);
                opFicheiro = sOPFicheiro.nextInt();
                     if (opFicheiro == 1){
                         System.out.println("A voltar ao menu anterior...");
                         Thread.sleep(1000);
                         editarFicheiro();
                     } else {
                            //Envia para um ArrayList o ficheiro Formandos
                            ArrayList<String> textoFormandos = new ArrayList<String>();
                            BufferedReader ler = new BufferedReader(new FileReader(FichFormandos));
                            String linha;
                        while ((linha = ler.readLine()) != null) {
                            textoFormandos.add(linha + "\n");
                        }
                        ler.close();
                              
                              //Remove , [ ] do ArrayList para enviar para o ficheiro
                              String textoFormandos2 = Arrays.toString(textoFormandos.toArray()).replace("[", "").replace("]", "").replace(",", "");
                         
                     }

文件: Txt File

save the ArrayList to a file

您的代码很幸运能够将数据写入文件。

在没有 try/catch 的情况下调用 close() 也是一种不好的做法,因为它会在出现异常时导致资源泄漏。

对于此任务,您不需要列表,找到与给定 id 的匹配项后,您可以将这些行写入文件。

要执行此代码文件 "test.txt" 必须位于项目文件夹下,文件 "result.txt" 将是自动创建。

    public static void main(String[] args) {
            try {
                readFile(Path.of("test.txt"), Path.of("result.txt"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    public static void readFile(Path target, Path result) throws InterruptedException {
        Scanner sOPFicheiro = new Scanner(System.in);
        int opFicheiro = sOPFicheiro.nextInt();
        if (opFicheiro == 1) {
            System.out.println("A voltar ao menu anterior...");
            Thread.sleep(1000);
            editarFicheiro();
        } else {

            try (BufferedReader ler = new BufferedReader(new FileReader(target.toFile()));
                 BufferedWriter br = new BufferedWriter(new FileWriter(result.toFile()))) {
                boolean matchIsFound = false;
                String linha;
                while ((linha = ler.readLine()) != null && !matchIsFound) {
                    if (linha.contains(String.valueOf(opFicheiro))) {
                        for (int i = 0; i < 5; i++) {
                            br.write(linha);
                            if (i != 4) {
                                br.newLine();
                                linha = ler.readLine();
                            }
                        }
                        matchIsFound = true;
                    }
                }
            }
            catch(IOException e) {
                e.printStackTrace();
            }
        }
    }

用户输入 - 1001

"test.txt" 文件的初始内容:

ID: 999
Name: ________________
Data of birth: _______
NIF: _________________
Telephone: ___________
Fim ID: 999

ID: 1001
Name: Cesar Rodrige da Silva Guimaraes
Data of birth: 16/03/2003
NIF: 1111111111
Telephone: 931111111111
Fim ID: 1001

执行代码后"result.txt"文件的内容:

ID: 1001
Name: Cesar Rodrige da Silva Guimaraes
Data of birth: 16/03/2003
NIF: 1111111111
Telephone: 931111111111

更新

    public static void main(String[] args) {
        try {
            updateUserData(Path.of("test.txt"), Path.of("temp.txt"));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void updateUserData(Path original, Path temp) throws InterruptedException {
        Scanner scanner = new Scanner(System.in);
        int id = scanner.nextInt();
        if (id == 1) {
            System.out.println("A voltar ao menu anterior...");
            Thread.sleep(1000);
            editarFicheiro();
            return;
        }

        String userData = readUserData(temp, id);
        String originalContentWithReplacement = readAndReplace(original, userData, id);
        writeData(original, originalContentWithReplacement);
    }
  • temp 文件中读取 user-data 给定的 id
    public static String readUserData(Path temp, int id) {
        StringBuilder result = new StringBuilder();
        try (var reader = new BufferedReader(new FileReader(temp.toFile()))) {
            boolean matchIsFound = false;
            String line;
            while ((line = reader.readLine()) != null && !matchIsFound) {
                if (line.contains(String.valueOf(id))) {
                    for (int i = 0; i < 5; i++, line = reader.readLine()) {
                        result.append(line).append(System.getProperty("line.separator"));
                    }
                    matchIsFound = true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString().stripTrailing();
    }
  • 读取原始文件的 whole contents 并替换给定 id
  • 的数据
    public static String readAndReplace(Path original, String userData, int id) {
        StringBuilder result = new StringBuilder();
        try (var reader = new BufferedReader(new FileReader(original.toFile()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.contains(String.valueOf(id))) {
                    result.append(line).append(System.getProperty("line.separator"));
                    continue;
                }

                result.append(userData).append(System.getProperty("line.separator"));
                for (int i = 0; i < 5; i++) {
                    line = reader.readLine();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString().stripTrailing();
    }
  • 替换之前的数据
    public static void writeData(Path original, String content) {
        try (var writer = new BufferedWriter(new FileWriter(original.toFile()))) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

而不是使用 ArrayList 使用 StringBuilder :

    StringBuilder textoFormandos = new StringBuilder();
    while ...
        textoFormandos.append(linha + "\n");
    ...
    String textoFormandos2 = textoFormandos.toString();

这样你就不需要删除任何东西。剩下的你需要明确要求。