Coder Social home page Coder Social logo

Comments (1)

looly avatar looly commented on June 12, 2024

@slysnight 确实存在不同JDK有差异……被JDK坑了。

5.8.28这块重新自己实现,参考:https://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java

	/**
	 * 计算文件的总行数<br>
	 * 参考:https://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java
	 *
	 * @param file       文件
	 * @param bufferSize 缓存大小,小于1则使用默认的1024
	 * @return 该文件总行数
	 * @since 5.8.28
	 */
	public static int getTotalLines(File file, int bufferSize) {
		if (false == isFile(file)) {
			throw new IORuntimeException("Input must be a File");
		}
		if (bufferSize < 1) {
			bufferSize = 1024;
		}
		try (InputStream is = getInputStream(file)) {
			byte[] c = new byte[bufferSize];
			int readChars = is.read(c);
			if (readChars == -1) {
				// 空文件,返回0
				return 0;
			}

			// 起始行为1
			// 如果只有一行,无换行符,则读取结束后返回1
			// 如果多行,最后一行无换行符,最后一行需要单独计数
			// 如果多行,最后一行有换行符,则空行算作一行
			int count = 1;
			while (readChars == bufferSize) {
				for (int i = 0; i < bufferSize; i++) {
					if (c[i] == CharUtil.LF) {
						++count;
					}
				}
				readChars = is.read(c);
			}

			// count remaining characters
			while (readChars != -1) {
				for (int i = 0; i < readChars; i++) {
					if (c[i] == CharUtil.LF) {
						++count;
					}
				}
				readChars = is.read(c);
			}

			return count;
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}
	}

from hutool.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.