Porque o código não exibe as informações?

3 respostas Resolvido
eclipseprogramaçãojava
Alexsandro_Andrade

bom dia, o código abaixo puxa as linhas de um arquivo TXT no entanto eu gostaria de imprimir somente as linhas que comecem com “02” mas ele não funciona. arquivo txt em anexotexto.txt (6,6 KB)

package layoutarquivos;

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

public class Exemplo {

public static void main(String[] args) {
	String linha;
	int i = 0;
	try {
		FileReader arq = new FileReader("texto.txt");
		BufferedReader lerarq = new BufferedReader(arq);
		try {

			linha = lerarq.readLine(); 
			while (linha != null && linha.substring(0, 2).equals("02")) {//se eu utilizar "01" como parametro ele funciona
				{
					System.out.println(linha);
					linha = lerarq.readLine();
					i++;
				}
			}
			System.out.println("valor de I - " + i);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	} catch (FileNotFoundException e) {
		System.out.println("arquivo nao encontrado");
		e.printStackTrace();
	}

}

}

3 Respostas

ardenghe

Bom dia amigo!

public static void main(String[] args) throws IOException {

        Scanner ler = new Scanner(System.in);
        String caminho = "C:\\Java\\texto.txt";
        try {
            int i = 0;
            FileReader arq = new FileReader(caminho);
            BufferedReader lerArq = new BufferedReader(arq);
            String linha = lerArq.readLine();
            while ((linha != null)) {
                if (linha.substring(0, 2).toString().equals("02")) {
                    System.out.println(linha);
                    linha = lerArq.readLine();
                    i++;
                } else {
                    linha = lerArq.readLine();
                }
            }
            System.out.println(i);
        } catch (IOException e) {
            System.err.printf("Erro na abertura do arquivo: %s.\n",
                    e.getMessage());
        }
    }
ardenghe
Solucao aceita

O erro está no while acho, com “01” funciona pois seu txt começa com 01… mas n mostraria os “01” recorrentes após outro valor diferente de “01”.

Alexsandro_Andrade

ardenghe, funcionou perfeitamente! obrigado!

Criado 31 de maio de 2017
Ultima resposta 31 de mai. de 2017
Respostas 3
Participantes 2