?
Solved

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

Posted on 2003-03-25
7
Medium Priority
?
220 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses
Course of the Month13 days, 13 hours left to enroll

801 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