getting # of lines in file

hello, how can i get the number of lines in a text file without looping though the lines?
LVL 4
91mustangAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
CEHJConnect With a Mentor Commented:
You could do something like this:


import java.util.regex.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
import java.io.*;

/**
 *  Description of the Class
 *
 * @author     CEHJ
 * @created    28 March 2004
 */
public class LineCount2 {

      public static void main(String[] args) throws Exception {
            if (args.length < 1) {
                  System.out.println("Usage: java LineCount2 <text file to count lines of>");
                  System.exit(-1);
            }
            int count = 0;
            FileChannel roChannel = new RandomAccessFile(new File(args[0]), "r").getChannel();
            ByteBuffer bbuf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) roChannel.size());
            CharBuffer cbuf = Charset.forName(System.getProperty("file.encoding")).newDecoder().decode(bbuf);

            Pattern EOL = Pattern.compile("\\n");
            Matcher matcher = EOL.matcher(cbuf);
            while (matcher.find()) {
                  count++;
            }
            if (cbuf.length() > 0) {
                  ++count;
            }
            System.out.println(count + " lines found");
      }

}
0
 
CEHJCommented:
You can't really. Why would you want to though?
0
 
91mustangAuthor Commented:
I have an app that reads a file in line parses line, inserts to DB,next line....

I want to use a Jprogress bar and use the number of lines in file as the maximum value for proggress bar
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
twobitadderCommented:
You'll need to do a pre-parse/dbInsertion parse to compare every character for '/n' and sum them.
0
 
91mustangAuthor Commented:
thanks CEHJ
0
 
CEHJCommented:
8-)
0
All Courses

From novice to tech pro — start learning today.