How do I read a particular java file position, and get the values from it?

Asked

Viewed 34 times

1

My code is as follows:

BufferedReader leitor = new BufferedReader (new FileReader("CARTEIRA\\Chart of accounts\\PlanConCxToReceive.txt"));
String texto = leitor.readLine();
String[] palavras = texto.split(" ->   ;");
 
while (texto !=null) {
    texto = leitor.readLine();
    System.out.println(palavras);     
}

My txt file has the following structure

Bills to receive teste -> 1000.0;
Bills to receive teste -> 200.0;

I want to take the two values and make a sum, I could not do at all.

1 answer

0

When you use split, have to specify the string that will be used to split.

How you used " -> ;", he will try to find exactly this stretch (space, hyphen, >, spaces and semicolons). But this sequence does not exist in your file, because after -> has a number, so the split won’t make the break the way you need it.

One way to solve is to do the break only by ->, then in the number you eliminate the ; manually. And finally, you convert the string to number and sum to total:

double total = 0;
try (BufferedReader leitor = new BufferedReader(new FileReader("CARTEIRA\\Chart of accounts\\PlanConCxToReceive.txt"))) {
    String texto;
    while ((texto = leitor.readLine()) != null) {
        String valor = texto.split(" -> ")[1];
        total += Double.parseDouble(valor.substring(0, valor.length() - 1));
    }
}
System.out.println(total); // 1200.0

In the case, valor.substring(0, valor.length() - 1) eliminates the last character (which is the ;), and Double.parseDouble converts the string to number. I chose this class because in the file the numbers have a decimal place, and parseDouble can handle it (Integer.parseInt would make a mistake, for example).

I also put the BufferedReader in a block Try-with-Resources (available from Java 7), which ensures that the file will be closed at the end.

And the program does not validate: it assumes that it will always have the -> and the second position always has a number. But if you want to validate, you can do something like this:

double total = 0;
try (BufferedReader leitor = new BufferedReader(new FileReader("CARTEIRA\\Chart of accounts\\PlanConCxToReceive.txt"))) {
    String texto;
    while ((texto = leitor.readLine()) != null) {
        String[] partes = texto.split(" -> ");
        if (partes.length > 1) {
            String valor = partes[1];
            try {
                total += Double.parseDouble(valor.substring(0, valor.length() - 1));
            } catch (NumberFormatException e) {
                // não é número - mostrar alguma mensagem de erro, ignorar, etc
            }
        } else {
            // linha não tem "->" - mostrar alguma mensagem de erro, ignorar, etc
        }
    }
}

Browser other questions tagged

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