End of file?

Hi, I'm trying to read a file. But how do I know when is the end of the file?

the file contains some words per line. So I use:

[CODE]infile.readLine()[/CODE]

I want to do a while loop like that:
[CODE]
while (NOT END OF FILE){
word.add(infile.readLine);
}
[/CODE]

How do we write in JAVA "NOT END OF FILE"?

Comments

  • : [CODE]infile.readLine()[/CODE]

    You don't say what class [b]infile[/b] is. Here is a Reader example:

    [code]
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.LineNumberReader;
    import java.io.Reader;

    public class ReadLines {

    public static int readLines(String file, String charEncoding)
    throws IOException {
    InputStream inputStream = null;
    Reader reader = null;
    LineNumberReader lineNumberReader = null;
    try {
    inputStream = new FileInputStream(file);
    reader = new InputStreamReader(inputStream, charEncoding);
    lineNumberReader = new LineNumberReader(reader);

    while (true) {
    String line = lineNumberReader.readLine();
    if (line == null) {
    //EOF
    break;
    }
    System.out.println(
    lineNumberReader.getLineNumber() + ": " + line);
    }
    return lineNumberReader.getLineNumber();
    } finally {
    if (lineNumberReader != null) {
    try {
    lineNumberReader.close();
    } catch (IOException e) {
    }
    }
    if (reader != null) {
    try {
    reader.close();
    } catch (IOException e) {
    }
    }
    if (inputStream != null) {
    try {
    inputStream.close();
    } catch (IOException e) {
    }
    }
    }

    }

    public static void main(String[] args) {
    try {
    String file = "ReadLines.java";
    String charEncoding = "UTF-8";
    int lineCount = readLines(file, charEncoding);
    System.out.println();
    System.out.println(lineCount + " lines in " + file);
    } catch (IOException e) {
    System.err.println("ERROR: " + e.getLocalizedMessage());
    e.printStackTrace();
    }
    }
    }

    [/code]

    ---------------------------------
    [size=1]HOWTO ask questions: http://catb.org/~esr/faqs/smart-questions.html[/size]

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion