Findind out the number of lines within a string - using buffered reader

Hi All,
Want to know the number of lines within a string..Sample code is there for reference..could u help me out how to have the number of lines in a string without java comments (i.e string within /**------*/ and // should be eliminated)
public class ReadLines {
     public static void main(String[] args) throws Exception{
          ReadLines rl = new ReadLines();
          rl.readLines();
     void readLines() throws Exception{
          String str = "/** This is a test message\n"+
               "* for testing\n"+
               "*/\n"+
               "import java.io.*\n"+
               "// this is again comment\n"+
               "public class ReadLines {\n"+
          BufferedReader reader = new BufferedReader(new StringReader(str));
          String line = "";
          int count = 0;
          while ((line = reader.readLine())!= null )
               //line = reader.readLine();
               count++;
          System.out.println(count);
}Thanks
MK

Hi
What you need to do is parse the file in such a way that you read /*, */ and // as tokens. By that I mean rather than read a line at a time (although I'm sure you could), read it character by character. So every time you reach a new line character then increment the counter. But there are two casaes when you don increment the counter they are:
If you encounter a / followed by * then keep reading but if you encounter a newline character then DONT increment the counter ONLY continue counting when you read a * followed by a / (as this is the end of the comment)
If you encounter / followed by another / then do not count that particular line and go to the next line and continue counting from there.
Where I've written 'continue counting' this is subject to the lines that follow not conforming to the above two cases.
I hope this helps.

Similar Messages

  • How can I find out the number of lines in a text file?

    How can I find out the number of lines in a text file?

    java.io.BufferedReader in = new java.io.BufferedReader( new java.io.FileReader( "YourFile.txt" ) );
    int lineCount = 0;
    while( in.readLine() != null )
    lineCount ++;
    System.out.println( "Line Count = " + lineCount );

  • Java Comiler - How to find out the Number of lines of Executable code

    Hello,
    Is there any option we have or could have to get the "Number of Lines of Executable Code" while we run the java compiler?
    Technically Java is an interpreter. So in case the term is incorrect, please excuse me.
    Since the compiler anyway traverses through the Java files, it is easy and correct to get the number from the compiler rather than having any external tool calculating the same.
    It should remove the comments, blank lines and take care of java single sentence written in multiple lines.
    Any suggestions or help is highly appreciated.
    regards,
    Sabyasachi

    How many lines of code are there in this program?
    public class sabre20110211 {public static void main(String[] args) {for (int i = 0; i < 10; i++)System.out.println(i);}}And how many in this program?
    public
            class
            sabre20110211
        public
                static
                void
                main(
                String[]
                args
            for
                    (int i = 0;
            i < 10;
            i++
                System.out.println(i);
    }

  • How can I get the number of lines in a string?

    I have a lone string with multiples lines (return). How can I find out how many lines in the string?

    For the counting of no.of lines, try the Line Counter here http://exchange.ni.com/servlet/ProcessRequest?RHIVEID=101&RPAGEID=135&HOID=506500000008000000BB700000&USEARCHCONTEXT_CATEGORY_0=_49_%24_6_&USEARCHCONTEXT_CATEGORY_S=0&UCATEGORY_0=_49_%24_6_&UCATEGORY_S=0
    As for extracting data without having worry over the description, you may wanna try using "Configuration File VI" in LabVIEW's File I/O function palletes.
    Regards
    ian.f
    Ian F
    Since LabVIEW 5.1... 7.1.1... 2009, 2010
    依恩与LabVIEW
    LVVILIB.blogspot.com

  • A quick way to count the number of  newlines '/n' in string of 200 chars

    I am trying to establish the number of lines that a string will generate.
    I can do this by counting the number of '/n' in the string. However my brute force method (shown below) is very slow.
    Normally this would not be a problem on a 2800mhz Athlon (Standard) PC this takes < 1 second. However this code resides within a speed critical loop (not shown). The code shown below is a Achilles heal as far as the performance of this speed critical loop goes.
    Can anyone suggest a faster way to count the number of �/n� (new lines) within a text string of around 50- 1000 chars, given that there may be 10 � 100 newline chars. Speed is a very important factor for this part of my program.
    Thanks in advance
    Andrew.
        int lineCount =0;
        String txt = this.getText();
        //loop throught text and count the carridge returns
        for (int i = 0; i < txt.length(); i++)
          char ch = txt.charAt(i);
          if (ch == '\n')
           lineCount ++;
        }//end forMessage was edited by:
    scottie_uk
    Message was edited by:
    scottie_uk

    Well, here is a C version. On my computer the Java version (reply 9 above) is slightly faster than C. YMMV. For stuff like this a compiler can be hard to beat even with assembler, as you need to do manual loop unrolling and method inlining which turn assembly into a maintenance nightmare.
    // gcc -O6 -fomit-frame-pointer -funroll-loops -finline -o newlines.exe newlines.c
    #include <stdio.h>
    #include <string.h>
    #if defined(__GNUC__) || defined(__unix__)
    #include <time.h>
    #include <sys/time.h>
    #else
    #include <windows.h>
    #endif
    #if defined(__GNUC__) || defined(__unix__)
    typedef struct timeval TIMESTAMP;
    void currentTime(struct timeval *time)
        gettimeofday(time, NULL);
    int milliseconds(struct timeval *start, struct timeval *end)
        int usec = (end->tv_sec - start->tv_sec) * 1000000 +
         end->tv_usec - start->tv_usec;
        return (usec + 500) / 1000;
    #else
    typedef FILETIME TIMESTAMP;
    void currentTime(FILETIME *time)
        GetSystemTimeAsFileTime(time);
    int milliseconds(FILETIME *start, FILETIME *end)
        int usec = (end->dwHighDateTime - start->dwHighDateTime) * 1000000L +
         end->dwLowDateTime - start->dwLowDateTime;
        return (usec + 500) / 1000;
    #endif
    static int count(register char *txt)
        register int count = 0;
        register int c;
        while (c = *txt++)
         if (c == '\n')
             count++;
        return count;
    static void doit(char *str)
        TIMESTAMP start, end;
        long time;
        register int n;
        int total = 0;
        currentTime(&start);
        for (n = 0; n < 1000000; n++)
         total += count(str);
        currentTime(&end);
        time = milliseconds(&start, &end);
        total *= 4;
        printf("time %ld, total %d\n", time, total);
        fflush(stdout);
    int main(int argc, char **argv)
        char buf[1024];
        int n;
        for (n = 0; n < 256 / 4; n++)
         strcat(buf, "abc\n");
        for (n = 0; n < 5; n++)
         doit(buf);
    }

  • Get number of character within a String by number of pixels

    How can i get the number of character within a String
    by a width value...
    for example..
    i have a String = "1234567890abcdefghi.........."
    and when i give the width "10"
    i will get the String "12".
    or the number of charcter..
    or somthingggggggggggggggg
    please help..
    Shay

    i solved this...
    by doing somthing similar..
    i made a for loop on all character
    and evrey time i am get a sub string from the 0 till the loop index..
    and i am chashing the last string
    so when a sub width is greater the the requested width
    i am returning the lst cashed result
    thanks.. all..

  • How to get the number of lines of a FileReader

    I need to calculate the number of lines of a FileReader object. How can I do that ?

    I wrote the following some while ago. It assumes that a line is terminated by '\n' but it should be easy to adapt.
    import java.io.*;
    public class LineCounter
        public static int countLines(File file, String encoding) throws IOException
            int lineCount = 0;
            Reader reader = new InputStreamReader(new FileInputStream(file), encoding);
            char[] buffer = new char[4096];
            for (int charsRead = 0; (charsRead = reader.read(buffer)) >= 0;)
                for (int charIndex = 0; charIndex < charsRead ; charIndex++)
                    if (buffer[charIndex] == '\n')
                        lineCount++;
            reader.close();
            return lineCount;
        public static void main(String[] args)
            try
                File file = new File("/home/sabre/work/dev/maps/EUROPE.RIV");
                long startTime = System.currentTimeMillis();
                int lineCount = countLines(file, "UTF-8");
                double time =  (System.currentTimeMillis() - startTime) / 1000.0;
                System.out.println("File size = " + file.length() + " contains " + lineCount + " lines taking " + time);
            catch (Exception e)
                e.printStackTrace();
    }

  • Increasing the number of line items in PO

    hello fellow abapers,
    i have a query. i dont know if its the headache of the function ppl or the technicial person - which happens to be me - but i have to get this solved at the earliest.
    now ive made a PO for materials from the scratch and everythin is workin fine. except that out of the blue comes a PO with over 10000 line items. yes, thats right - 10,000 line items.
    so obviously an error was thrown by SAP. unfortunately the end-user did not think it necessary to take a printout or record the error message.
    anyways the error said something to the effect that it did not allow so many line items or somthing like that.
    now can anybody pls help me out with this. firstly is dhere any restrictions on the number of line items, and secondly, if thats the case how do i find a work-around.
    thanx a bunch
    pk

    Hi,
    The basis sets the maximum number of pages that can be printed by the user in authorization object S_SPO_PAGE.
    Please discuss with your basis guy.
    Tyken

  • Count the number of lines in  each file in a directory

    Hello,
    I would like to count the number of lines for each file in my directory and subdirectories.
    I wonder how can I count the lines of the specified files?
    Here is the program which is listed the files in the specified directory:
                        String path = "C:/User/Studies/Pracices/src/Pract1";
           String files;
           File folder = new File(path);
           File[] listOfFiles = folder.listFiles();
           for (int i = 0; i < listOfFiles.length; i++)
            if (listOfFiles.isFile())
         files = listOfFiles[i].getName();
         System.out.println(files);

    Ok so one more question.
    Actually my path is pointing to one Directory and like here I can just read from one file that the name of the file should be specified in the path is it possible to help me in that part?
    File f = new File("C:/User/Studies/Practices/src/Pract1/");
    FileReader fr = new FileReader(f);
          BufferedReader br = new BufferedReader(fr);
          String str = br.readLine();
              LineNumberReader ln = new LineNumberReader(br);
              int count = 0;
              while (ln.readLine()!=null)
                  count++;
              System.out.println("no. of lines in the file = " + count);

  • Java Program+To count the number of lines in a method excluding comments???

    Hi friends
    can u plz help me out, the java program is counting the number of lines in a method excluding comments.
    The first thing is how to identify a method, then there can be an inner method inside the parent method,
    Please friends its urgent
    Bye
    Sandy

    There's no such thing as an inner method in Java. You can either write the code yourself to parse Java source, or maybe something like ANTLR can do it.

  • Count the number of Lines with in a method

    I am trying to write a program that will report back the number of methods/types/names and proxies as well as the number of lines of code in each method... I can not figure out how to count each methods line of code separately thanks. each method is commented by
    /* PROXY proxyname type */
    /* METHOD method name*/
    public class Assignment3
    private static BufferedReader userInput = new BufferedReader (new InputStreamReader (System.in));
         * @param args
         * @throws IOException
         * @param args
         * @throws IOException
         public static void main(String[] args) throws IOException
              System.out.print("Enter the .java file name: ");
         String input = userInput.readLine();
         while (!input.equalsIgnoreCase("stop"))
              System.out.println("Total Number of Lines: " + LOC(input) + "\n" + Method(input) + "\n" + Type(input));
              System.out.print("\nEnter file name to search again or \"stop\" to terminate the program: ");
              input = userInput.readLine();
    public static int LOC(String inputFile) throws IOException, FileNotFoundException
         int numLines = 0;
         try
                        FileReader FileIn = new FileReader(inputFile);
                        Scanner scanLines = new Scanner (FileIn);
                        String line;
                             while (scanLines.hasNext())
                                  line = scanLines.nextLine();
                                  if (line.startsWith("/*"))
                                       numLines--;
                                  else if(!line.equals(" "))
                                       numLines++;
                             FileIn.close();
              catch(IOException IOE)
                   System.out.println("\nFile Not Found!");
                   return numLines;
    public static int MethodLOC(String inputFile) throws IOException, FileNotFoundException
         File FileIn = new File(inputFile);
         Scanner scanLines = new Scanner (FileIn);
         String line = null;
         int methodLOC = 0;
         while(scanLines.hasNext())
              line = scanLines.nextLine();
              if(!line.contains("/*"))
                   StringTokenizer st = new StringTokenizer(line, "\n");
                   methodLOC = st.countTokens();
         return methodLOC;
    public static String Method(String inputFile) throws IOException, FileNotFoundException
         String line = null;
         String name = null;
         String info = null;
         File FileIn = new File(inputFile);
         Scanner scanLines = new Scanner (FileIn);
         while(scanLines.hasNext())
              line = scanLines.nextLine();
         if(line.contains("METHOD"))
              StringTokenizer st = new StringTokenizer(line, " ");
              String proxy = st.nextToken();
              String method = st.nextToken();
              name = st.nextToken();
              info = "Name of Method: " + name;
    return info;
    public static String Type(String inputFile) throws IOException, FileNotFoundException
         String line = null;
         String name = null;
         String info = null;
         String count = null;
         File FileIn = new File(inputFile);
         Scanner scanLines = new Scanner (FileIn);
         while(scanLines.hasNext())
         if(line.contains("PROXY"))
              StringTokenizer st = new StringTokenizer(line, " ");
              String proxy = st.nextToken();
              String method = st.nextToken();
              name = st.nextToken();
              String type = st.nextToken();
              info = "Name of Proxy: " + name + "\n" + "Type of Proxy: " + type;
         count = info;
    return count;
    }

    Iterate through the lines and count the opening and closing curly braces. Whenever you see an opening one, increase the counter, when you see a closing one, decrease the counter. When the counter hits 0 again, you reached the end of the method.
    I assume you know how to count lines while moving through a text line by line.

  • How do you find the number of lines in a file?

    I need to count how many lines there are in a file, I am using a BufferedReader to read in the data, but how can I find the number of lines?
    Thanks

    That depends. How do you define a line? Is it a specific number of
    characters, a String that's terminated by a newline character or some
    combination thereof?

  • How do I increase the number of lines presented in a drop down list?

    When I am entering a single character/number for each of a random selection of three letters in a password verification, I get a drop down list from A to S only, the first 20. Accessing letter T to number 9 means scrolling down. How can I increase the number of lines in a drop down box to 36?

    Hi canddski,
    If you are taking about an interface on a website, this is up to the ui designer. But there is a reflow that depends on screensize for the Firefox UI.
    You can use asp to control the list:
    [http://forums.asp.net/t/1970301.aspx?How+can+i+display+selected+no+of+records+from+datatable+using+dropdown+list+without+database+]
    but also try asking on stackoverflow.com

  • How to get the number of lines of a file?

    Folks:
    Is there a way to get the number of lines of a text file? I don't know if there is an existing method to do that.
    Thanks a lot.

    HI
    I found some solution
    other than increment loop and all
    here is the code it might helpful to u
    //returns the number of lines in a file
    //author : Ravindra S
    //Symphony software Hyderabad
    try
    RandomAccessFile randFile = new RandomAccessFile(csvFile,"r");
    long lastRec=randFile.length();
    randFile.close();
    FileReader fileRead = new FileReader(csvFile);
    LineNumberReader lineRead = new LineNumberReader(fileRead);
    lineRead.skip(lastRec);
    countRec=lineRead.getLineNumber()-1;
    fileRead.close();
    lineRead.close();
    catch(IOException e)

  • How to find out the number of threads created under java vm at runtime

    our application seems to have hit the max number of threads that can be created under vm and the vm will just hang after that. that behavior seems to be consistent from an article that I read earlier.
    I wonder any way that java app can find out the number of threads currently created under vm?
    thanks in advance!

    If you are not starting an extra thread group you can use the Thread.activeCount method. But this willnot return all the threads, as there are some jvm threads, i.e. garbage collector. Also if you are running on a Unix type operating system then you can send a signal to the jvm to give you a thread dump, i think the signal is sighup.
    If the application is hanging i would of thought that you have a deadlock situation rather then the JVM not being able to create new threads, roughly how many threads should be running ??

Maybe you are looking for

  • Inter company STO-how to reduce the stock where no physical stock is kept in receiving plant

    Dear All, I am facing one issue. Suppose if there are two plants belongs to two company codes A & B.Plant A is in TN & Plant B is in AP (both belongs to two different states). Plant B is the place where no physical stock is kept, it is a place where

  • SQL 2008 Reporting Services: Setting BackgroundRepeat = NoRepeat in SQL 2008

    Good day I have an report that has a background image set.  The BackgroundRepeat property = Clip (which is the alternative to 2005 NoRepeat). This background image is only suppose to print on the first page. When the report was still in SQL 2005 it p

  • Error while using execute immediate

    Hi, I am trying to get the record count of a table. The table name is saved in a variable.. when i am writing the code like below its working fine. SELECT count(*) into count1 FROM emp1; DBMS_OUTPUT.PUT_LINE(count1); but when i am using the code for

  • Banking Vendor Info not updated from HR Banking infotype

    Hi Gurus, I have an issue  and I can't quite for sure know  how to solve it. My HR team are able to change the banking info of the vendors/employees( employees are also treated as vendors) ....  When we run a report or job  for employee's direct depo

  • Need help with load balancing and DNS proxy

    Hi, I need help on how to configure my router so it will work with my DNS proxy and load balancing. I have a Linksys LRT224 router. I have two broadband connections from two separate ISPs,500Mbps each (WAN1 & WAN2). WAN1 has a static IP and WAN2 is d