Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q4008 How do I read a text/data file into an array?

irt.org | Knowledge Base | Java | Q4008 [ previous next ]

Q4008 How do I read a text/data file into an array?

You use a combination of URL object and DataInputStream, Like shown below the example takes a file data.dat which is an ascii text file in the same directory as the calling class,

   /*
    * The URL data loader for the pattern a.k.a. File handling
    * for an applet 
    * We need to have the data file 
    * data.dat in the same directory as this applet (i.e same CodeBase)
    */
   void loadData(){
      URL u=null;
      DataInputStream inFile=null;
      
      try{
    u=new URL(getCodeBase(),"data.dat");
    inFile=new DataInputStream(u.openStream());
  
      /*
       * Instantiate our 5 variables now by reading one line
       * per variable from data.dat
       */

       for (int i=0;i<5;i++){
            c[i]=new String(inFile.readLine()); // c[] an array of strings
        }
            }catch (Exception ee){   // Maybe just a bad connection!
            return; // no point in proceeding now
      }

      /*
       * If we reloaded all values
       * then we should regenerate our other parameter, variables etc.
       */
      updateDataRoutine(); // Handle calculations on data here
   }// end loadData()

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 6th July 2009. Maintained by: Martin Webb
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2009 irt.org, All Rights Reserved.