5 Replies Latest reply: Feb 25, 2008 7:34 AM by 807601 RSS

    End of File Constant in Java

    807601
      Hello. Could someone tell me how to access the EOF constant in Java.
        • 1. Re: End of File Constant in Java
          807601
          -1
          FileInputStream myFile = null;
          try {
            myFile = new  FileInputStream("abc.dat");  // open the  stream
            boolean eof = false;
          
            while (!eof) {
              int byteValue = myFile.read();        // read  the stream  
              if (byteValue  == -1)
                eof = true;
            }
            //myFile.close();          // do not do it here!!!
          } catch (IOException e) {
            System.out.println("Could not read file: " + e.toString());
          } finally{
            try{
              myFile.close();                           // close the stream
            } catch (Exception e1){
              e1.printStackTrace();
            }
          }
          ie, reading bytes from an input stream results -1 if there are no more bytes available to read. See http://java.sun.com/javase/6/docs/api/java/io/FileInputStream.html#read()
          • 2. Re: End of File Constant in Java
            807601
            Thanks so much. If I am reading the file line by line with the randomaccessfile method readLine(), how can I check to see when I reach the eof character? Presently I use this loop

            for (String line = getLine.readLine(); line != null;
            line = getLine.readLine())

            I just want to be able to read the whole file then exit.
            • 3. Re: End of File Constant in Java
              807601
              Same goes here, according to the API:
              http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html#readLine()
              It returns null when the EOF has been reached.
              • 4. Re: End of File Constant in Java
                807601
                Oba_Shonowo wrote:
                Thanks so much. If I am reading the file line by line with the randomaccessfile method readLine(), how can I check to see when I reach the eof character? Presently I use this loop

                for (String line = getLine.readLine(); line != null;
                line = getLine.readLine())

                I just want to be able to read the whole file then exit.
                You don't need a RandomAccessFile to read the lines of a file. You would do better to use a BufferedReader using code very similar to that you have just given.
                • 5. Re: End of File Constant in Java
                  807601
                  Why do you check for null in your for loop? What's the reason.

                  Read the API documentation of readLine (found at http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html#readLine() ) and you'll know.