Contar linhas de um arquivo

6 respostas
Andre_Rosa

Olá, preciso imprimir a quantidade de linhas de um arquivo de texto. Uma vez fiz isso em C, e o que fiz foi percorrer o arquivo até o fim e contar os \n, que representa, assim como em Java, quebra de linha. Pois bem, em Java, para eu fazer o mesmo, eu devo fazer da mesma forma, ou há alguma forma mais simples ou alguma classe que pode me ajudar?

Grato.

6 Respostas

nextuser
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class LineReader {

	public static void main(String[] args) throws Exception {
		LineNumberReader lineCounter = new LineNumberReader(new InputStreamReader(new FileInputStream("C:\MyFile.txt")));
		String nextLine = null;

		try {
			while ((nextLine = lineCounter.readLine()) != null) {
				if (nextLine == null)
					break;
				System.out.println(nextLine);
			}
			System.out.println("Total number of line in this file " + lineCounter.getLineNumber());
		} catch (Exception done) {
			done.printStackTrace();
		}
	}
}
Andre_Rosa

Obrigado. Mas me fica a dúvida: qual palavra chave se refere ao fim do arquivo? Como EOF (End of File), em C?

Obrigado.

nextuser

não existe

Andre_Rosa

Então como funciona?

Notei que esse trecho é o responsável por percorrer o arquivo:

while ((nextLine = lineCounter.readLine()) != null)

mas como ele sabe onde é o fim, e qual foi o critério para saber a quantidade de linhas?

Obrigado! ^^

O_Monge

http://download.oracle.com/javase/1.4.2/docs/api/java/io/LineNumberReader.html#readLine()

public String readLine() throws IOException

Read a line of text. A line is considered to be terminated by any one of a line feed (’\n’), a carriage return (’\r’), or a carriage return followed immediately by a linefeed.

Overrides:
readLine in class BufferedReader

Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

Throws:
IOException - If an I/O error occurs

kenneth

Complementando, mais especificamente esta parte:

Abraco.

Criado 11 de abril de 2011
Ultima resposta 12 de abr. de 2011
Respostas 6
Participantes 4