How to get data from a text file with java?

0

I have a text file with some data in the following notation [[name: Ricardo]] and I need a function that identifies this mark in the middle of the file, and returns the string with the name in question. I've been tempted to do so with a loop running through the file for the square brackets, but I wonder if there is any way to accomplish this that is simpler and faster.

    
asked by anonymous 31.05.2016 / 21:27

1 answer

1

You could maybe use regular expression in this case:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class testeajuda {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        File diretorio = new File("C:\testes\"); //Diretório de entrada 
        File[] arquivos = diretorio.listFiles();

        if (arquivos != null) {
            for (int i = 0; i < arquivos.length; ++i) {
                if (arquivos[i].getName().endsWith("txt")) {
                    File f = arquivos[i];
                    FileReader reader = new FileReader(f);
                    BufferedReader input = new BufferedReader(reader);
                    String linha = "";
                    String teste = "";
                    while ((linha = input.readLine()) != null) {
                        Matcher matcher = Pattern.compile(":\s\w*").matcher(linha); // Primeiro Filtro (Pega tudo que tem :, espaço, e tudo que vem depois que seja alfanumerico)
                        while (matcher.find()) {

                            Pattern pattern = Pattern.compile(":\s"); // Segundo Filtro (Elimina o ":" e o espaço)
                            Scanner scanner = new Scanner(matcher.group()).useDelimiter(pattern);
                            Matcher matcher2 = pattern.matcher(teste);
                            while (scanner.hasNext()) {
                                teste = scanner.next(); 
                                System.out.println(teste); // retorna apenas "Ricardo"
                            }
                        }
                    }

                }
            }
        }
    }
}
    
08.07.2016 / 21:10