import java.io.File; import java.io.FileReader; import java.io.LineNumberReader; public class FileLinelength { public static void main(String args[]) throws Exception{ File file = new File("C:\\work\\hello\\helloworld.txt"); FileReader reader = new FileReader(file); LineNumberReader lineReader = new LineNumberReader(reader); int length = 0; while(lineReader.readLine()!= null){ length++; } System.out.println("This file line number is " + length); } }
Perforcemance比較高的方法 java
public int count(String filename) throws IOException { InputStream is = new BufferedInputStream(new FileInputStream(filename)); try { byte[] c = new byte[1024]; int count = 0; int readChars = 0; boolean empty = true; while ((readChars = is.read(c)) != -1) { empty = false; for (int i = 0; i < readChars; ++i) { if (c[i] == '\n') { ++count; } } } return (count == 0 && !empty) ? 1 : count; } finally { is.close(); } }
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("File1"))); lnr.skip(Long.MAX_VALUE); System.out.println(lnr.getLineNumber());