Buscar una cadena en un archivo .txt y obtener el número de fila y columna en Java

rododendro:

Actualmente estoy atascado con un problema. Se supone que debo escribir una Programm que es capaz de buscar una cadena en un archivo .txt dado como argumento. El programm debe devolver la fila y la columna de la cadena encontrada. Estoy luchando para encontrar una manera de lograr eso y no tienen idea de cómo continuar. Estaría muy feliz de saber de usted.

Aquí está mi intento de hacer frente con mi tarea: - pensé en salvar el contenido de un archivo a través de un lector de tampón en una matriz de cadenas, pero que no parece que el trabajo ya que no puedo definir la longitud de la matriz desde el principio - I también pensó en salvar el contenido del archivo a través de un lector de tampón en una cadena y luego dividir esta cadena en caracteres. Sin embargo no estoy seguro de cómo voy a ser capaz de retreieve las filas en el archivo original a continuación.

El código no funcional que tengo en este momento:

public class StringSearch{
    public static void main(String[] args){
        if(args.length > 0){
            BufferedReader br = null;
            String text = null;
            try{
                br = new BufferedReader(new FileReader(args[0]));
                // attempt of saving the content of the "argument" file in a string array and then in a        string
                String[] lines = new String[]; // I know this does not work like this 
                for( int i = 0; i < lines.length; i++){
                    lines[i] = br.readLine;
                    text = text + lines[i];
                    i++;
                }
                text.split("\r\n");

            } catch (IOException ioe){
                ioe.printStackTrace();
            } finally{
                if (br != null) {
                    try{
                        br.close();
                    }catch (IOException ioe){
                        ioe.printStackTrace();
                    }
                }


            }

        }
    }
}

Arvind Kumar Avinash:

Puede hacerlo de la siguiente manera:

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("The correct syntax to use this program is: java Main <filename.txt> <text-to-search>");
            return;
        }
        Scanner scanner;
        File file = new File(args[0]);
        int rowCount = 1, index;
        String line;

        // Map to collect row and col info of the search string
        Map<String, String> lineColMap = new HashMap<String, String>();

        if (!file.exists()) {
            System.out.println("The file, " + args[0] + " does not exist");
            return;
        }
        try {
            scanner = new Scanner(file);
            while (scanner.hasNextLine()) {// Loop until the last line in the file
                line = scanner.nextLine();// Read a line from the file
                index = line.indexOf(args[1]);// Find if the string exists in the line
                if (index != -1) {// If the string exists
                    // Put the row and col info of the search string into the map
                    lineColMap.put("Row: " + rowCount, "Column: " + index);
                }
                rowCount++;// Increase the row count
            }
        } catch (Exception e) {
            System.out.println("Error occured while processing the file");
            e.printStackTrace();
        }
        if (lineColMap.entrySet().size() > 0) {// If there is at least one entry collected into the map
            System.out.println("'" + args[1] + "' exists in " + args[0] + " as follows:");
            for (Map.Entry<String, String> entry : lineColMap.entrySet()) {
                System.out.println(entry.getKey() + ", " + entry.getValue());
            }
        } else {
            System.out.println("'" + args[1] + "' does not exist in " + args[0]);
        }
    }
}

Un análisis de la muestra: java Main input.txt of

'of' exists in input.txt as follows:
Row: 1, Column: 51
Row: 2, Column: 50
Row: 3, Column: 50
Row: 5, Column: 71

El contenido de input.txtes el siguiente:

Stack Overflow is a question and answer site for professional and enthusiast programmers.
It is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky.
It features questions and answers on a wide range of topics in computer programming.
It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange.
The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.

La lógica en el código es sencillo y creo, debe ser capaz de entender que en la primera lectura. Siéntase libre de comentar en caso de cualquier duda.

Supongo que te gusta

Origin http://10.200.1.11:23101/article/api/json?id=477190&siteId=1
Recomendado
Clasificación