Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

How do I tell if I am at the EOF when using a DataInputStream?

Posted on 2003-03-25
7
Medium Priority
?
221 Views
Last Modified: 2010-03-31
I am having a hard time finding out when I reach the end of my file.  The all variables is an array of 5 NAMEs.  When I call the the below method, it should read each name from the file and stop when there is no more data in the file or the end of the array.  The file is Unicode and is created by the read method in the NAME class.  If your wondering why my class names are UPPERCASS, its cause I started it a few days ago after finishing a COBOL assignment and my brain wasn't working right :)


void Open_actionPerformed(ActionEvent e)
  {
    FileDialog D = new FileDialog(this, "Open Name File");
    D.setModal(true);
    D.setVisible(true);
    if(D.getFile() == null) return; // No File Selected
    String fileName = D.getDirectory() + D.getFile();
   
    try{
      in = new DataInputStream(new FileInputStream(new File(fileName)));
      for(int i=0; i<all.length && in != null; i++)
         NAME.read(in, this);
      in.close();
      in = null;

    }catch(IOException err){
      new ERRDIALOG(this, err.getMessage());
    }
  }


// My Code from my NAME class.


import java.io.*;
import java.awt.*;

public class NAME
{

  static final int NAME_LEN = 30;
  protected String firstName;
  protected String lastName;

  public NAME(String firstname, String lastname)throws NAMEEXCPTION
  {
    setFirstName(firstname.trim());
    setLastName(lastname.trim());
  }


  public void write(DataOutputStream out) throws IOException
  {
    int Lfirst = NAME_LEN - firstName.length();
    int Llast = NAME_LEN - lastName.length();
    String name = firstName;
    for(int i=0; i<Lfirst; i++)
        name += " ";
    out.writeChars(name);
    String lname = lastName;
    for(int i=0; i<Llast; i++)
        lname += " ";
    out.writeChars(lname);

  }

  static NAME read(DataInputStream in, Frame frame)
  {
    String FName = "";
    String LName = "";

    try{

      for(int i=0; i<NAME_LEN; i++)
        FName += in.readChar();

      for(int i=0; i<NAME_LEN; i++)
        LName += in.readChar();

      return new NAME(FName.trim(), LName.trim());

    }catch(IOException err){
      new ERRDIALOG(frame, err.getMessage());
    }catch(NAMEEXCPTION err){
      new ERRDIALOG(frame, err.getMessage());
    }
    System.out.println("Returning Null");
    return null; //should never reach this point.
  }

  void setFirstName(String name) throws NAMEEXCPTION
  {
    if(name == null || name.length() == 0)
      throw new NAMEEXCPTION("Name Format Error: Name cannot be: blank");
    else
      firstName = name;
  }

  void setLastName(String name) throws NAMEEXCPTION
  {
    if (name == null || name.length() == 0)
      throw new NAMEEXCPTION("Name Format Error: Name cannot be: blank");
    else
      lastName = name;
  }

  public String getFirstName(){return firstName;}
  public String getLasntName(){return lastName;}

  public String toString( )
  {
    return firstName+", " +lastName;
  }


  public static void main(String[] args)
  {
    try{
      NAME name = new NAME("Dan", "Demers");
      Frame f = new Frame("Frame Name");
      FileDialog D = new FileDialog(f, f.getTitle());
      D.setVisible(true);
      D.setModal(true);
      String file = D.getDirectory() + D.getFile();
      DataOutputStream out = new DataOutputStream(new FileOutputStream(file));
      name.write(f, out);out.flush();
      out.close();
      DataInputStream in = new DataInputStream(new FileInputStream(file));
      NAME N = name.read(in, f);
      in.close();
      System.out.println(N);

    }catch(Exception err){
      err.printStackTrace();
    }
    System.exit(0);
  }

}
0
Comment
Question by:FaithNoMore
  • 2
  • 2
  • 2
  • +1
7 Comments
 

Accepted Solution

by:
chryso earned 80 total points
ID: 8208086
FaithNoMore:

A DataInputStream can also throw a EOFException, which occurs when the DataInputStream tries to perform a read at the End Of File. In your read(DataInputStream in, Frame frame) method, you can add another catch statement that catches a EOFException, from there you can handle the EOF however you wish.

Hope this helps!

-Chryso
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8208263
I guess the returned character from readChar () can also be type-casted to an int and checked if its equal to -1. If yes, then its the EOF character, otherwise, it can be appended to the string.

Mayank.
0
 

Expert Comment

by:chryso
ID: 8208402
Actually, a DataInputStream won't return -1 (unlike every other type of InputStream, which indeed perform as mayankeagle stated).  A DataInputStream is subclassed from a FilteredInputStream, which removes the -1 return code in favor of throwing an EOFException.  I cannot verify this, but I think a FilteredInputStream wraps the read() method of an InputStream and performs additional filtering, hence the name.

Cheers,

-C.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 30

Expert Comment

by:Mayank S
ID: 8208447
You're right.... readChar () will throw it, but I tried it with read ().... that won't. It'll allow the EOF to be detected by comparing the returned value with -1.

Mayank.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8209159
Why don't you just make the NAME class serializable and save it to a file with ObjectOutputStream? It'd be a hell of a lot easier than what you're doing.

out.writeObject(new NAME("Charlie", "Chaplin"));

Read it back:

NAME name = (NAME)in.readObject();
0
 
LVL 1

Author Comment

by:FaithNoMore
ID: 8209821
CEHJ

saving it as an object would be prefer to use readObject/writeObject, but this is part of a school assignment where we learn how to read different types of data.  Thanks for the thought though.


chryso

I will try EOFException, then post results or further problems, thanks.
0
 
LVL 1

Author Comment

by:FaithNoMore
ID: 8210030
Thanks for the help chryso


Encase someone stumbles on this thread, I've posted the working code.

 void Open_actionPerformed(ActionEvent e)
  {
    FileDialog D = new FileDialog(this, "Open Name File");
    D.setModal(true);
    D.setVisible(true);
    if(D.getFile() == null) return; // No File Selected
    String fileName = D.getDirectory() + D.getFile();

    try{
      in = new DataInputStream(new FileInputStream(new File(fileName)));

      for(int i=0; i<all.length; i++)
      {
        NAME n = NAME.read(in, this);
        if(n == null) break;          //EOF
        all[i] = n;
        System.out.println(i+"");
     }

      in.close();
      in = null;
      updateNames(); //Updates Fields


// read method from the NAME class.

 static NAME read(DataInputStream in, Frame frame)
  {
    String FName = "";
    String LName = "";

    try{

      for(int i=0; i<NAME_LEN; i++)
        FName += in.readChar();

      for(int i=0; i<NAME_LEN; i++)
        LName += in.readChar();

      NAME n = new NAME(FName, LName);
      return n;

    }catch(EOFException err){
      return null;
    }
    catch(IOException err){
      new ERRDIALOG(frame, err.getMessage());
    }catch(NAMEEXCPTION err){
      new ERRDIALOG(frame, err.getMessage());
    }
    System.out.println("Returning Null");
    return null; //should never reach this point.
  }
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Don’ts and Dos are two important end products of software testing basics that a tester needs to regard. This article attempts to explain the principles of both.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month11 days, 21 hours left to enroll

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question