Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 348
  • Last Modified:

getting # of lines in file

hello, how can i get the number of lines in a text file without looping though the lines?
0
91mustang
Asked:
91mustang
  • 3
  • 2
1 Solution
 
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
 
CEHJCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help 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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now