How to get file line count.

Hey guys,
How to get file line count very fast? I am using BufferedReader to readLine() and count. But when dealing with big file, say several GB size, this process will be very time consuming.
Is there any other methods?
Thanks in advace!

What I'd do is you create an infofetcher, register a listener, implement gotMore() and have that scan for '\n'
Some might suggest getting rid of the listener/sender pattern or use multiple threads to make ii faster. This might help a little, but only if your I/O is super-duper speedy.
you are welcome to use and modify this code, but please don't change the package or take credit for it as your own work.
InfoFetcher.java
============
package tjacobs.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
* InfoFetcher is a generic way to read data from an input stream (file, socket, etc)
* InfoFetcher can be set up with a thread so that it reads from an input stream
* and report to registered listeners as it gets
* more information. This vastly simplifies the process of always re-writing
* the same code for reading from an input stream.
* <p>
* I use this all over
     public class InfoFetcher implements Runnable {
          public byte[] buf;
          public InputStream in;
          public int waitTime;
          private ArrayList mListeners;
          public int got = 0;
          protected boolean mClearBufferFlag = false;
          public InfoFetcher(InputStream in, byte[] buf, int waitTime) {
               this.buf = buf;
               this.in = in;
               this.waitTime = waitTime;
          public void addInputStreamListener(InputStreamListener fll) {
               if (mListeners == null) {
                    mListeners = new ArrayList(2);
               if (!mListeners.contains(fll)) {
                    mListeners.add(fll);
          public void removeInputStreamListener(InputStreamListener fll) {
               if (mListeners == null) {
                    return;
               mListeners.remove(fll);
          public byte[] readCompletely() {
               run();
               return buf;
          public int got() {
               return got;
          public void run() {
               if (waitTime > 0) {
                    TimeOut to = new TimeOut(waitTime);
                    Thread t = new Thread(to);
                    t.start();
               int b;
               try {
                    while ((b = in.read()) != -1) {
                         if (got + 1 > buf.length) {
                              buf = IOUtils.expandBuf(buf);
                         int start = got;
                         buf[got++] = (byte) b;
                         int available = in.available();
                         //System.out.println("got = " + got + " available = " + available + " buf.length = " + buf.length);
                         if (got + available > buf.length) {
                              buf = IOUtils.expandBuf(buf, Math.max(got + available, buf.length * 2));
                         got += in.read(buf, got, available);
                         signalListeners(false, start);
                         if (mClearBufferFlag) {
                              mClearBufferFlag = false;
                              got = 0;
               } catch (IOException iox) {
                    throw new PartialReadException(got, buf.length);
               } finally {
                    buf = IOUtils.trimBuf(buf, got);
                    signalListeners(true);
          private void setClearBufferFlag(boolean status) {
               mClearBufferFlag = status;
          public void clearBuffer() {
               setClearBufferFlag(true);
          private void signalListeners(boolean over) {
               signalListeners (over, 0);
          private void signalListeners(boolean over, int start) {
               if (mListeners != null) {
                    Iterator i = mListeners.iterator();
                    InputStreamEvent ev = new InputStreamEvent(got, buf, start);
                    //System.out.println("got: " + got + " buf = " + new String(buf, 0, 20));
                    while (i.hasNext()) {
                         InputStreamListener fll = (InputStreamListener) i.next();
                         if (over) {
                              fll.gotAll(ev);
                         } else {
                              fll.gotMore(ev);
InputStreamListener.java
====================
package tjacobs.io;
     public interface InputStreamListener {
           * the new data retrieved is in the byte array from <i>start</i> to <i>totalBytesRetrieved</i> in the buffer
          public void gotMore(InputStreamEvent ev);
           * reading has finished. The entire contents read from the stream in
           * in the buffer
          public void gotAll(InputStreamEvent ev);
InputStreamEvent
===============
package tjacobs.io;
* The InputStreamEvent fired from the InfoFetcher
* the new data retrieved is from <i>start</i> to <i>totalBytesRetrieved</i> in the buffer
public class InputStreamEvent {
     public int totalBytesRetrieved;
     public int start;
     public byte buffer[];
     public InputStreamEvent (int bytes, byte buf[]) {
          this(bytes, buf, 0);
     public InputStreamEvent (int bytes, byte buf[], int start) {
          totalBytesRetrieved = bytes;
          buffer = buf;
          this.start = start;
     public int getBytesRetrieved() {
          return totalBytesRetrieved;
     public int getStart() {
          return start;
     public byte[] getBytes() {
          return buffer;
ParialReadException
=================
package tjacobs.io;
public class PartialReadException extends RuntimeException {
     public PartialReadException(int got, int total) {
          super("Got " + got + " of " + total + " bytes");
}

Similar Messages

  • How to get file count in variable?

    dear all,
    how to get file count in variable?
    regards
    Naseer

    Hi Nazeer ,
    It wont take much time .. so simple :- )
    Create one os comand step
    ( for unix) Use
    wc -l filename.txt > someoutputfile.txt
    Now the number of lines in your file will be there in the output file ( someoutputfile.txt )
    Step2 :-
    Now use Cezar's logic to fetch the variable value ( file count ) from the output file .. ( select value for a variable from a file )
    This will not take eeven a second to finish the job.
    Regards,
    Rathish A M

  • How to get 2nd line in smartforms using template

    how to get 2nd line in smartforms main window using template. i have also defined loop .

    if possible can you try with the TABLES..
    Put one TABLE in your MAIN window
    create table lines as per your requirment...consider all lines like 6 for header, 1 for main, 1 for total
    Now, you will find three section under the tables: header, main, footer...
    in header section, create a table line, assign one of the proper lines from the line types.. repeat for your all lines.
    in main section, you can access your data form the loop.
    the footer secion will be called, just after the main will be finished.
    Regards,
    Naimesh Patel

  • How to get file from server while click on link

    Hi,
    i created on link and i gave one server path to select file from server but while clickinng on link it no displaying any thing.
    following is the Destination url that i gave for the item.
    /u08/app/appvis/xxex/inst/xxex_apps/xxrbe/logs/appl/conc/log/
    please tell me how to get file from server while click on link.

    Ok I got your requirement now.
    If you are getting file names from view attribute then you should not be adding destination URI property for the link.
    Instead you can use OADataBoundValueViewObject API.
    Try below code in your controller processRequest method:
    I am assuming that you are using classic table.
    Also in below example it considers OAMessageStyleText and you can replace it with link item if you want.
    OATableBean tableBean =
    (OATableBean)webBean.findChildRecursive("<table item id>");
    OAMessageStyledTextBean m= (OAMessageStyledTextBean)tableBean.findChildRecursive("<message styled text in table item id>");
    OADataBoundValueViewObject tip1 = new OADataBoundValueViewObject(m, "/u08/app/appvis/xxex/inst/xxex_apps/xxrbe/logs/appl/conc/log/"+"<vo attr name which stores file name for each row>");
    m.setAttributeValue(oracle.cabo.ui.UIConstants.DESTINATION_ATTR, tip1);
    Regards,
    Sandeep M.

  • How to get the row Count of a ResultSet

    How to get the row Count of a ResultSet

    Hi
    I'v tried rennie1's way ,but I only get zero,my code is:
    rs.executeQuery("select count(*) from t_test");
    if (rs.next()) int rowCount=rs.getInt(1);
    I also tried barni's way ,but the method rs.last() and rs.beforeFirst() throw a same Exception
    I tried another way,the code is:
    while rs.next(){
    // Do nothing ,just move the cursour to the last row
    int rowCount=rs.getRow()
    However,the rowCount still equal zero
    Any help would be greatly apprecite!
    note:
    I get connection by DataSource's JNDI name from client, the Server is Weblogic Server 6, the DBMS is Oracle.

  • How to get trending line in the graph

    Hi,
    I am using 10g. I have requirement as the following :
    Name Date Metric
    I can have bar graph against Date and Metric. My requirement is to have a trending line, so I calculated slope and regression line y=mx+c but I am not getting the right trend line. I can use regr_slope function to create a view in rpd but it doesnt support date values. Can you guys let me know how to get trending line like same in Excel.
    Thanks

    Hi,
    It's better to do at UI level.
    Can you please check the below link:
    http://kpipartners.blogspot.in/2009/04/linear-regression.html
    Hope this helps.
    Thanks,
    Pramod.

  • How to get the line in the template (smartform) with out using under score

    Hi,
         How to get the line in the template (smartform) with out using under score,
         and how to print the box (line the check box - small squre box (which is used ot mark the tick by the user in front of the item).
         Please provide the valueble answer as early as possible.
    Thanks,
    Ravi

    Hi Ravi,
    Line -
    Use a SMATSTYLE for this purpose.in the smartstyle create a paragraph or character with underline atribute.Then call the smartstyle in the text.
    Search SDN with Key <b>UNDERSCORE</b>.. will get few more posts on the same.
    For Checkbox - refer link
    Re: Quick Question on Smartforms
    Re: putting tick mark into check box in smartform
    Reward points if this Helps.
    Manish
    Message was edited by:
            Manish Kumar

  • How to get file attribs - on any Mac

    ok so if the Mac in question has Developer / Tools - yeah the GetFileInfo binary will work to get the Type and Creator code and other info.... since most Macs dont have this bulky download... how to get file attribute information via Terminal ? How to change it ?

    Oddly enough I was just now playing around with a getinfo Applescript and studying the event log when I realized that it does return information about at least some of the attributes. I made the ones that it looks like you can get information about bold:
    A Alias file
    B Bundle
    C Custom icon
    D Desktop
    E Hidden extension
    I Inited
    M Shared (can run multiple times)
    N No INIT resources
    L Locked
    S System (name locked)
    T Stationary
    V Invisible
    Z Busy
    If you are interested see this thread:
    http://discussions.apple.com/message.jspa?messageID=5261906#5261906
    The SetFile function is actually available on any Mac that has a recent Tiger updater package installed. Thus I have copies in both the package updaters and the receipts for 10.4.7, .8, .9 and .10 in the /Library/Packages and /Library/Receipts folders. The SetFile command is in the Resources folder:
    "/Library/Packages/MacOSXUpd10.4.10PPC.pkg/Contents/Resources/SetFile"
    Control click on the .pkg file and select Show contents from the Contextual Menu to get there. Unfortunately I don't know of any way to use some other Terminal command to get information on all the attributes, except the GetFileInfo and using the Applescipt get info function.
    Francine
    Francine
    Schwieder

  • How to get File type icon for files store on Amazons3

    Hi,
    i want to know about how to get file type icons for files that we store on Amazons3.i am a devloper ,i want to make gui for accessing amazons3.
    so ,i want to know about how to get file type icons for files that we store on Amazons3.
    thanx in advance.

    hi,
    have u heard amazon simple storage service,that provides storage space for
    storing files, i am a devloper,i want to know the files that we store on amazon,how we can get file type icon for that files.
    i want to sample code in java for this.
    thanx in advance.

  • How to get  visible row  count  in JTable ?

    I have one table which is added to one scroll pane. For example my table have total 1000 rows, but at a time only 20 rows should be visible to the scroll pane. And I want to scroll the rows and show only 20 at a time.When user scrolls JTable then next time he can view only 1 to 21, then 2 to 22, and so on. I want to know how to get that number which represents the visible row( in this case it is 20).So kindly help me how to get visible row count. Any help regarding this will be appriciated.
    Thanks and Regards,
    Sheetal

    how to get visible row count.First you need to get the viewport used by the scrollpane. Then you can use methods like getViewPosition() and getViewSize() to get information about the current postition of and size of the viewport.
    Then you can use the table method getRowAtPoint(). to determine the first and last visible row which can then be used to calculate the visible row count.
    When user scrolls JTable then next time he can view only 1 to 21, then 2 to 22, and so onThis is the default behaviour when a "block" scroll is done.
    However when you click on the arrow button on the scrollbar it will only scroll a single row. You could override the getScrollableUnitIncrement() method to return the value from the getScrollableBlockIncrement() method.
    However the user can still drag the scrollbar manually which would cause a problem. So you would also need to remove the MouseMotionListeners from the scrollbar to prevent this.

  • How to get succesfullt loaded count in forall

    hi,
    plz tell me how to get succefuly loaded count into a table if i m using bulk collect & forall .

    Check out the documentation:
    Counting Rows Affected by FORALL with the %BULK_ROWCOUNT Attribute
    The cursor attributes SQL%FOUND, SQL%ISOPEN, SQL%NOTFOUND, and SQL%ROWCOUNT, return useful information about the most recently executed DML statement. For additional description of cursor attributes, see "Implicit Cursors".The SQL cursor has one composite attribute, %BULK_ROWCOUNT, for use with the FORALL statement. This attribute works like an associative array: SQL%BULK_ROWCOUNT(i) stores the number of rows processed by the ith execution of an INSERT, UPDATE or DELETE statement.

  • How to get the column count at the bottom of the column

    Hi Friends,
    How to get the column count at the bottom of the column
    Thanks
    Raj

    You mean row count? Add another column, click on the fx button and type RCOUNT(1).
    If you want just the total you can make it MAX(RCOUNT(1)), hide this column and then add a Narrative View after your report and enter "Total Number of Records: @n" where "n" represents what order your column is from the left side.

  • Getting file descriptor counts as a non-root user

    I have a number of scripts running on Solaris 8 and Solaris 10 systems that currently run as root in order to read file descriptor counts from various processes. currently they do something like: ls /proc/$PID/fd | wc -l to get a count of file descriptors for a given process $PID.
    These scripts need to be migrated to run as a non-root user. This means that my method for obtaining file descriptors will only work if the script owner and process owner are the same - this is not always the case however.
    For Solaris 10, I can assign the privilege proc_owner to the script owner - this works fine.
    For Solaris 8 I'm stuck.
    Does anyone have any idea how I can read a file descriptor count from an arbitrary process as a non-root user on Solaris 8 ?
    Thanks,
    Nick

    For Solaris 8 I'm stuck.
    Does anyone have any idea how I can read a file descriptor count from an
    arbitrary process as a non-root user on Solaris 8 ?As I'm sure you suspect there isn't a way to get around the all privileges
    or none arrangement in Solaris 8. One workaround option though is the
    recently announced Solaris 8 Migration Assistant 1.0 which allows you to
    run a Solaris 8 container on Solaris 10 SPARC systems. A good collection
    of the relevant links are here:
    http://blogs.sun.com/dp/entry/solaris_8_migration_assistant_1
    With this option your Solaris 10 script process with the proc_owner
    privilege could also be run against the processes in the Solaris 8
    container.
    Hope this helps.
    Brent

  • How to get a line break

    Hi All,
    How do I get a line break within a particular field?
    My DB structure is that I have 4 columns address_line_1, address_line_2 and so on. I cannot select them as different fields because all of them can be null, in which case i pick it from internal_address_line column.
    I use:
    SELECT DECODE(address_line_1, NULL, internal_address_line, address_line_1 || ', ' || Address_Line_2) as ADDRESS
    But instead of th comma separating the 2 address lines I want a line break so that 2 address lines come in 2 separate lines in the output.
    It doesn't allow me to use chr(10) as a line break and gives an error
    I'm using Reports 2.5
    TIA
    Naveen

    Yes, true.
    How about setting up the sections as:
    Section 1 Introduction ('Section num space introduction' in this example - tab may be better)
    Then generate the Contents.
    Then do a GREP find/change on the document after the contents:
    This will add a forced line break and tab after each section number... You might want to specify a para style in the Find Format box too, so that references to Section xx in body text are not altered.
    If you update Contents after this, you will get the line break and tab in the Contents too.

  • How to get File name in Proxy program

    Hi,
    According to my business scenario, one XML file name comes from Legacy system and stores in a predefined directory. Now XI has to pick up that XML file and needs to call BAPI's which in turn updates the Target system ( SAP Tables).
    Now my problem is , XML File name is a combination of three fileds those are DATE , OBJECTKEY AND WORKFLOWNAME.
    Ex : YYYYMMDD_1234565789_WORKFLOWNAME.XML
         DATE_OBJECTKEY_WORKFLOWNAME.XML
    In proxy i need to get the file name and split into three fields ( those are DATE , OBJECTKEY AND WORKFLOWNAME ) which needs to send as import parameters in BAPI's.
    So please let me know from anyone in this group how to get the file name in the proxy program.
    Thanks & Regards
    K. naveen Kumar

    Hi,
    have a look at my new weblog:
    /people/michal.krawczyk2/blog/2005/11/10/xi-the-same-filename-from-a-sender-to-a-receiver-file-adapter--sp14
    to see how you can access filename
    Regards,
    michal

Maybe you are looking for