Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
I'm using scanner to read a text file line by line but then how to get line number since scanner iterates through each input?My program is something like this: s = new Scanner(new BufferedReader(new FileReader("input.txt"))); while (s.hasNext()) { System.out.print(s.next()); This works fine but for example: 1,2,3 3,4,5 I want to know line number of it which mean 1,2,3 is in line 1 and ...
Possible Duplicate: Number of lines in a file in Java I need to count the number of lines of a txt file that is passed to java through a command line argument. I know how to read from a file but i am having trouble doing the rest. any help would be appreciated. here is what i have so far: import java.util.*; import java.io.*; public class LineCounter { public static void m...
Is there a C# equivalent of Java's LineNumberReader? i.e. a StreamReader.ReadLine() which kept count of the line number. Or is the only way to achieve this by creating a custom subclass of StreamReader, and implement the necessary counting in an overridden method?
Lets say I have 10 lines in a file. I have 2 parameters that specify the beginning and ending of a index. StartIndex = 2 // specifies the first 2 lines EndIndex = 3 // specifies the last 3 lines I need to read the lines in between. I know maintaining index and skipping is one of the ways...but are there any other efficient ways (even with external libraries)? Thanks
When I read the text file using Java, how can I skip first three rows of the text file? Current program, public class Reader { public static void main(String[] args) { BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader( new FileInputStream("sample.txt"))); Map<String, Integer> result = new LinkedHashMap&...
My text file contains a known number of lines (the first line of the file is the number of lines). I want to randomly read a line from the file - to do this I use LineNumberReader. The problem is, that it doesn't generate a new string - the random number changes but the string it gets from the LineNumberReader doesn't. As the title implies this is an Android app. textbox is the output area, te...
I require searching a word in a text file and display the line number using java. If it appears more than once I need to show all the line numbers in the output. Can anyone help me please?
I have been researching how to do this and becoming a bit confused, I have tried so far with Scanner but that does not seem to preserve line breaks and I can't figure out how to make it determine if a line is a line break. I would appreciate if anyone has any advice. I have been using the Scanner class as below but am not sure how to even check if the line is a new line. Thanks for (Strin...
I am using buffered reader to grab a line at a time from a text file. I am trying to also get the line number from the text file using a tracking integer. Unfortunately BufferedReader is skipping empty lines (ones with just /n or the carriage return). Is there a better way to solve this? Would using scanner work? Example code: int lineNumber = 0; while ((s = br.readLine()) != null) { ...
Error in following code- Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type IOException import java.io.*; public class Inp { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); ...
I need to search a file for a word and return the whole line and the line number with this word, then edit the line and write back to the file. Maybe the line number isn't necesary to edit a line in a file. I `was reading after seraching with regexp and opening the filechannel of the file, but I can't get the line number. Maybe there are other better ways to do this. Can you help me how to star...
  /*
   * Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.io;


A buffered character-input stream that keeps track of line numbers. This class defines methods setLineNumber(int) and getLineNumber() for setting and getting the current line number respectively.

By default, line numbering begins at 0. This number increments at every line terminator as the data is read, and can be changed with a call to setLineNumber(int). Note however, that setLineNumber(int) does not actually change the current position in the stream; it only changes the value that will be returned by getLineNumber().

A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Author(s):
Mark Reinhold
Since:
JDK1.1
 
 
 public class LineNumberReader extends BufferedReader {

    
The current line number
 
     private int lineNumber = 0;

    
The line number of the mark, if any
 
     private int markedLineNumber// Defaults to 0
 
    
If the next character is a line feed, skip it
 
     private boolean skipLF;

    
The skipLF flag when the mark was set
 
     private boolean markedSkipLF;

    
Create a new line-numbering reader, using the default input-buffer size.

Parameters:
in A Reader object to provide the underlying stream
 
     public LineNumberReader(Reader in) {
         super(in);
     }

    
Create a new line-numbering reader, reading characters into a buffer of the given size.

Parameters:
in A Reader object to provide the underlying stream
sz An int specifying the size of the buffer
 
     public LineNumberReader(Reader inint sz) {
         super(insz);
     }

    
Set the current line number.

Parameters:
lineNumber An int specifying the line number
See also:
getLineNumber()
 
     public void setLineNumber(int lineNumber) {
         this. = lineNumber;
     }

    
Get the current line number.

Returns:
The current line number
See also:
setLineNumber(int)
    public int getLineNumber() {
        return ;
    }

    
Read a single character. Line terminators are compressed into single newline ('\n') characters. Whenever a line terminator is read the current line number is incremented.

Returns:
The character read, or -1 if the end of the stream has been reached
Throws:
IOException If an I/O error occurs
    public int read() throws IOException {
        synchronized () {
            int c = super.read();
            if () {
                if (c == '\n')
                    c = super.read();
                 = false;
            }
            switch (c) {
            case '\r':
                 = true;
            case '\n':          /* Fall through */
                ++;
                return '\n';
            }
            return c;
        }
    }

    
Read characters into a portion of an array. Whenever a line terminator is read the current line number is incremented.

Parameters:
cbuf Destination buffer
off Offset at which to start storing characters
len Maximum number of characters to read
Returns:
The number of bytes read, or -1 if the end of the stream has already been reached
Throws:
IOException If an I/O error occurs
    public int read(char cbuf[], int offint lenthrows IOException {
        synchronized () {
            int n = super.read(cbufofflen);
            for (int i = offi < off + ni++) {
                int c = cbuf[i];
                if () {
                     = false;
                    if (c == '\n')
                        continue;
                }
                switch (c) {
                case '\r':
                     = true;
                case '\n':      /* Fall through */
                    ++;
                    break;
                }
            }
            return n;
        }
    }

    
Read a line of text. Whenever a line terminator is read the current line number is incremented.

Returns:
A String containing the contents of the line, not including any line termination characters, or null if the end of the stream has been reached
Throws:
IOException If an I/O error occurs
    public String readLine() throws IOException {
        synchronized () {
            String l = super.readLine();
             = false;
            if (l != null)
                ++;
            return l;
        }
    }

    
Maximum skip-buffer size
    private static final int maxSkipBufferSize = 8192;

    
Skip buffer, null until allocated
    private char skipBuffer[] = null;

    
Skip characters.

Parameters:
n The number of characters to skip
Returns:
The number of characters actually skipped
Throws:
IOException If an I/O error occurs
java.lang.IllegalArgumentException If n is negative
    public long skip(long nthrows IOException {
        if (n < 0)
            throw new IllegalArgumentException("skip() value is negative");
        int nn = (int) Math.min(n);
        synchronized () {
            if (( == null) || (. < nn))
                 = new char[nn];
            long r = n;
            while (r > 0) {
                int nc = read(, 0, (int) Math.min(rnn));
                if (nc == -1)
                    break;
                r -= nc;
            }
            return n - r;
        }
    }

    
Mark the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point, and will also reset the line number appropriately.

Parameters:
readAheadLimit Limit on the number of characters that may be read while still preserving the mark. After reading this many characters, attempting to reset the stream may fail.
Throws:
IOException If an I/O error occurs
    public void mark(int readAheadLimitthrows IOException {
        synchronized () {
            super.mark(readAheadLimit);
             = ;
                 = ;
        }
    }

    
Reset the stream to the most recent mark.

Throws:
IOException If the stream has not been marked, or if the mark has been invalidated
    public void reset() throws IOException {
        synchronized () {
            super.reset();
             = ;
                 = ;
        }
    }
New to GrepCode? Check out our FAQ X