Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

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

You are here: irt.org | FAQ | Java | Q4008 [ previous next ]

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()

©2018 Martin Webb