Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help on file write and read

Status
Not open for further replies.

zhanghong920

Programmer
Nov 15, 2002
27
US
I have a FileWriter object "outputfile", and use:
outputfile.write(w+ " ");
in a while loop to write the value in array w[]. Now,
how can I read the values from the outputfile next time? I use FileReader.read() as below, but it doesn't work.

FileReader vectorFile = new FileReader("d:/...");
vectorFile.read(tmpValueStr);
ncol = Integer.parseInt(tmpValueStr.toString());

Any suggestions? Besides, what's the best way to write/read a file of a array of integer/double?
Thanks a lot!

Hong
 
Hi zhanghong

Check that you are writing a whole vector on the stream.
If you want, for example, to write a single double value contained in a vector (w={1,2,3,4,5,6} and you want to write 123456 as a single value) you can iterate the vector and acumulate the value in a String:

String singlevalue="";
for(int i=0;i<w.length;i++) singlevalue+=&quot;&quot;+w\[i\];


and then write the double in the file:

output.write(new Double(singlevalue));


then you can read it like:

Double value=(Double) reader.readObject();


I don't know if that's what you need.
Hope it helps.
 
You also wanted to know the best way to read and write large arrays of ints and doubles. Since arrays are considered objects in Java, I'd recommend using the ObjectOutputStream and ObjectInputStream classes. I don't usually use arrays with these, but I believe they will function the way you want them.

For example,
Code:
// assume we have double[] arrDouble and int[] arrInt.

ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(&quot;file.dat&quot;));
oos.WriteObject(arrDouble);
oos.WriteObject(arrInt);
oos.Close();

ObjectInputStream ois=new ObjectInputStream(new FileInputStream(&quot;file.dat&quot;));
double[] newArrDouble=(double[])ois.ReadObject();
int[] newArrInt=(int[])ois.ReadInt();
ois.Close();
Just an example, but that's roughly how it ought to work.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top