[英]Number of lines in a file in Java
我使用巨大的數據文件,有時我只需要知道這些文件的行數,通常我打開它們並逐行讀取它們,直到到達文件的末尾
我想知道是否有更聰明的方法來做到這一點
這是迄今為止我發現的最快的版本,比 readLines 快大約 6 倍。 在 150MB 的日志文件上,這需要 0.35 秒,而使用 readLines() 時需要 2.40 秒。 只是為了好玩,linux 的 wc -l 命令需要 0.15 秒。
public static int countLinesOld(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();
}
}
編輯,9 1/2 年后:我幾乎沒有 Java 經驗,但無論如何,我已經嘗試將此代碼與下面的LineNumberReader
解決方案進行基准測試,因為沒有人這樣做讓我感到困擾。 似乎特別是對於大文件,我的解決方案更快。 盡管在優化器完成體面的工作之前似乎需要運行幾次。 我對代碼進行了一些操作,並生成了一個始終最快的新版本:
public static int countLinesNew(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int readChars = is.read(c);
if (readChars == -1) {
// bail out if nothing to read
return 0;
}
// make it easy for the optimizer to tune this loop
int count = 0;
while (readChars == 1024) {
for (int i=0; i<1024;) {
if (c[i++] == '\n') {
++count;
}
}
readChars = is.read(c);
}
// count remaining characters
while (readChars != -1) {
System.out.println(readChars);
for (int i=0; i<readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
readChars = is.read(c);
}
return count == 0 ? 1 : count;
} finally {
is.close();
}
}
1.3GB 文本文件的基准測試結果,y 軸以秒為單位。 我已經使用同一個文件執行了 100 次運行,並使用System.nanoTime()
測量了每次運行。 您可以看到countLinesOld
有一些異常值,而countLinesNew
沒有,雖然它只是快了一點,但差異在統計上是顯着的。 LineNumberReader
顯然更慢。
我已經實現了另一個解決方案,我發現它在計算行數方面更有效:
try
(
FileReader input = new FileReader("input.txt");
LineNumberReader count = new LineNumberReader(input);
)
{
while (count.skip(Long.MAX_VALUE) > 0)
{
// Loop just in case the file is > Long.MAX_VALUE or skip() decides to not read the entire file
}
result = count.getLineNumber() + 1; // +1 because line index starts at 0
}
對於不以換行符結尾的多行文件,接受的答案有一個錯誤。 沒有換行符結尾的單行文件將返回 1,但沒有換行符結尾的兩行文件也將返回 1。 這是解決此問題的已接受解決方案的實現。 除了最終讀取之外,endsWithoutNewLine 檢查對於所有內容都是浪費的,但與整體功能相比應該是微不足道的。
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 endsWithoutNewLine = false;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n')
++count;
}
endsWithoutNewLine = (c[readChars - 1] != '\n');
}
if(endsWithoutNewLine) {
++count;
}
return count;
} finally {
is.close();
}
}
使用java-8 ,您可以使用流:
try (Stream<String> lines = Files.lines(path, Charset.defaultCharset())) {
long numOfLines = lines.count();
...
}
如果文件末尾沒有換行符,上面方法 count() 的答案給了我行錯誤計數 - 它無法計算文件中的最后一行。
這種方法對我更有效:
public int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
int cnt = 0;
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {}
cnt = reader.getLineNumber();
reader.close();
return cnt;
}
我測試了上述計算線的方法,這里是我對在我的系統上測試的不同方法的觀察
文件大小:1.6 Gb 方法:
此外, Java8方法似乎很方便:
Files.lines(Paths.get(filePath), Charset.defaultCharset()).count()
[Return type : long]
我知道這是一個老問題,但接受的解決方案與我需要它做的並不完全匹配。 ).因此,我改進了它以接受各種行終止符(而不僅僅是換行符)並使用指定的字符編碼(而不是 ISO-8859- )。 多合一方法(酌情重構):
public static long getLinesCount(String fileName, String encodingName) throws IOException {
long linesCount = 0;
File file = new File(fileName);
FileInputStream fileIn = new FileInputStream(file);
try {
Charset encoding = Charset.forName(encodingName);
Reader fileReader = new InputStreamReader(fileIn, encoding);
int bufferSize = 4096;
Reader reader = new BufferedReader(fileReader, bufferSize);
char[] buffer = new char[bufferSize];
int prevChar = -1;
int readCount = reader.read(buffer);
while (readCount != -1) {
for (int i = 0; i < readCount; i++) {
int nextChar = buffer[i];
switch (nextChar) {
case '\r': {
// The current line is terminated by a carriage return or by a carriage return immediately followed by a line feed.
linesCount++;
break;
}
case '\n': {
if (prevChar == '\r') {
// The current line is terminated by a carriage return immediately followed by a line feed.
// The line has already been counted.
} else {
// The current line is terminated by a line feed.
linesCount++;
}
break;
}
}
prevChar = nextChar;
}
readCount = reader.read(buffer);
}
if (prevCh != -1) {
switch (prevCh) {
case '\r':
case '\n': {
// The last line is terminated by a line terminator.
// The last line has already been counted.
break;
}
default: {
// The last line is terminated by end-of-file.
linesCount++;
}
}
}
} finally {
fileIn.close();
}
return linesCount;
}
這個解決方案在速度上與公認的解決方案相當,在我的測試中慢了大約 4%(盡管 Java 中的計時測試是出了名的不可靠)。
/**
* Count file rows.
*
* @param file file
* @return file row count
* @throws IOException
*/
public static long getLineCount(File file) throws IOException {
try (Stream<String> lines = Files.lines(file.toPath())) {
return lines.count();
}
}
在 JDK8_u31 上測試。 但與此方法相比,性能確實很慢:
/**
* Count file rows.
*
* @param file file
* @return file row count
* @throws IOException
*/
public static long getLineCount(File file) throws IOException {
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(file), 1024)) {
byte[] c = new byte[1024];
boolean empty = true,
lastEmpty = false;
long count = 0;
int read;
while ((read = is.read(c)) != -1) {
for (int i = 0; i < read; i++) {
if (c[i] == '\n') {
count++;
lastEmpty = true;
} else if (lastEmpty) {
lastEmpty = false;
}
}
empty = false;
}
if (!empty) {
if (count == 0) {
count = 1;
} else if (!lastEmpty) {
count++;
}
}
return count;
}
}
經過測試,速度非常快。
使用 Scanner 的直接方式
static void lineCounter (String path) throws IOException {
int lineCount = 0, commentsCount = 0;
Scanner input = new Scanner(new File(path));
while (input.hasNextLine()) {
String data = input.nextLine();
if (data.startsWith("//")) commentsCount++;
lineCount++;
}
System.out.println("Line Count: " + lineCount + "\t Comments Count: " + commentsCount);
}
我得出結論, wc -l
:s 計算換行符的方法很好,但在最后一行不以換行符結尾的文件上返回非直觀結果。
和基於 LineNumberReader 的 @er.vikas 解決方案,但在最后一行以換行符結尾的文件上,在行數中添加一個返回非直觀結果。
因此,我做了一個處理如下的算法:
@Test
public void empty() throws IOException {
assertEquals(0, count(""));
}
@Test
public void singleNewline() throws IOException {
assertEquals(1, count("\n"));
}
@Test
public void dataWithoutNewline() throws IOException {
assertEquals(1, count("one"));
}
@Test
public void oneCompleteLine() throws IOException {
assertEquals(1, count("one\n"));
}
@Test
public void twoCompleteLines() throws IOException {
assertEquals(2, count("one\ntwo\n"));
}
@Test
public void twoLinesWithoutNewlineAtEnd() throws IOException {
assertEquals(2, count("one\ntwo"));
}
@Test
public void aFewLines() throws IOException {
assertEquals(5, count("one\ntwo\nthree\nfour\nfive\n"));
}
它看起來像這樣:
static long countLines(InputStream is) throws IOException {
try(LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is))) {
char[] buf = new char[8192];
int n, previousN = -1;
//Read will return at least one byte, no need to buffer more
while((n = lnr.read(buf)) != -1) {
previousN = n;
}
int ln = lnr.getLineNumber();
if (previousN == -1) {
//No data read at all, i.e file was empty
return 0;
} else {
char lastChar = buf[previousN - 1];
if (lastChar == '\n' || lastChar == '\r') {
//Ending with newline, deduct one
return ln;
}
}
//normal case, return line number + 1
return ln + 1;
}
}
如果你想要直觀的結果,你可以使用這個。 如果你只是想要wc -l
兼容性,簡單使用 @er.vikas 解決方案,但不要在結果中添加一個並重試跳過:
try(LineNumberReader lnr = new LineNumberReader(new FileReader(new File("File1")))) {
while(lnr.skip(Long.MAX_VALUE) > 0){};
return lnr.getLineNumber();
}
如何在 Java 代碼中使用 Process 類? 然后讀取命令的輸出。
Process p = Runtime.getRuntime().exec("wc -l " + yourfilename);
p.waitFor();
BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
int lineCount = 0;
while ((line = b.readLine()) != null) {
System.out.println(line);
lineCount = Integer.parseInt(line);
}
不過需要嘗試一下。 將發布結果。
這個有趣的解決方案實際上非常有效!
public static int countLines(File input) throws IOException {
try (InputStream is = new FileInputStream(input)) {
int count = 1;
for (int aChar = 0; aChar != -1;aChar = is.read())
count += aChar == '\n' ? 1 : 0;
return count;
}
}
LineNumberReader 似乎有幾種不同的方法。
我這樣做了:
int lines = 0;
FileReader input = new FileReader(fileLocation);
LineNumberReader count = new LineNumberReader(input);
String line = count.readLine();
if(count.ready())
{
while(line != null) {
lines = count.getLineNumber();
line = count.readLine();
}
lines+=1;
}
count.close();
System.out.println(lines);
更簡單的是,您可以使用 Java BufferedReader lines() 方法返回元素流,然后使用 Stream count() 方法對所有元素進行計數。 然后只需在輸出中添加 1 即可獲得文本文件中的行數。
例如:
FileReader input = new FileReader(fileLocation);
LineNumberReader count = new LineNumberReader(input);
int lines = (int)count.lines().count() + 1;
count.close();
System.out.println(lines);
在基於 Unix 的系統上,在命令行上使用wc
命令。
知道文件中有多少行的唯一方法是計算它們。 您當然可以根據您的數據創建一個指標,為您提供一行的平均長度,然后獲取文件大小並將其除以 avg。 長度,但這不會是准確的。
如果您沒有任何索引結構,您將無法閱讀完整的文件。 但是您可以通過避免逐行讀取並使用正則表達式來匹配所有行終止符來優化它。
在 EOF 處沒有換行符 ('\\n') 的多行文件的最佳優化代碼。
/**
*
* @param filename
* @return
* @throws IOException
*/
public static int countLines(String filename) throws IOException {
int count = 0;
boolean empty = true;
FileInputStream fis = null;
InputStream is = null;
try {
fis = new FileInputStream(filename);
is = new BufferedInputStream(fis);
byte[] c = new byte[1024];
int readChars = 0;
boolean isLine = false;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if ( c[i] == '\n' ) {
isLine = false;
++count;
}else if(!isLine && c[i] != '\n' && c[i] != '\r'){ //Case to handle line count where no New Line character present at EOF
isLine = true;
}
}
}
if(isLine){
++count;
}
}catch(IOException e){
e.printStackTrace();
}finally {
if(is != null){
is.close();
}
if(fis != null){
fis.close();
}
}
LOG.info("count: "+count);
return (count == 0 && !empty) ? 1 : count;
}
帶有正則表達式的掃描儀:
public int getLineCount() {
Scanner fileScanner = null;
int lineCount = 0;
Pattern lineEndPattern = Pattern.compile("(?m)$");
try {
fileScanner = new Scanner(new File(filename)).useDelimiter(lineEndPattern);
while (fileScanner.hasNext()) {
fileScanner.next();
++lineCount;
}
}catch(FileNotFoundException e) {
e.printStackTrace();
return lineCount;
}
fileScanner.close();
return lineCount;
}
沒計時過
如果你使用這個
public int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
int cnt = 0;
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {}
cnt = reader.getLineNumber();
reader.close();
return cnt;
}
你不能跑到大 num 行,比如 100K 行,因為從 reader.getLineNumber 返回的是 int。 您需要長類型的數據來處理最大行數..
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.