|
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()
|
|
|
Copyright © 1996-2009 irt.org, All Rights Reserved.