How to make a program in Java search in a certain information file and return a string

Asked

Viewed 1,342 times

2

Hello. I have a program that would have to search in a text file like this:

ovelha animal
gato animal
joão humano
arvore planta

I need a method, which receiving a string, evaluates based on that file if that string is there, for example the method receives the string "cat", which is there then it returns the string "animal", if it received the string "john" would return the string "human"And so on, but if you got something that’s not on the list, you’d return "error," or something like that. I have no idea how to do this :P Thanks in advance

  • Hi, first: You use the File class to search for the file.2º you have to "read" the file and then use methods like contains or index of the String class to check the information you are looking for.

  • You can try passing each line of your file to a String, which in turn would be added in a List<String>. Once this is done, you will need to do the treatment as follows: take what you have before the blank space (search for trim()) and make the comparison within a repeat loop (for or while of life). When there is correspondence, take what is left of the String (despise what you have before the white space) and use it as your return. PS: I’m on my way home and I couldn’t explain with code, but I hope the line of thought helps you.

1 answer

4


 import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.Scanner;

public class Teste {
    public static void main(String[] args) throws FileNotFoundException {

        String chave = "gato";
        String local = "C:\\Users\\kcpo\\Desktop\\farm.txt";
        System.out.println(getValor(chave, local));
    }
    private static String getValor(String chave, String local)
            throws FileNotFoundException {
        String valor = "";
        Scanner in = new Scanner(new FileReader(local));
        while (in.hasNextLine()) {
            String line = in.nextLine();
            String[] linha = line.split(" ");

            if (linha[0].equals(chave)) {
                valor = linha[1];
                break;
            } else {
                valor = "erro";
            }
        }
        return valor;
    }
}
  • 1

    Thanks, it worked here!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.