Contar linhas de um arquivo

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.

[code]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();
	}
}

}[/code]

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

Obrigado.

não existe

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! ^^

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

[quote]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[/quote]

Complementando, mais especificamente esta parte:

Abraco.

1 curtida