I cannot figure out how to read in data after I have saved it
The problem is that I’m using the write method of the FileOutputStream class. The docs I read said this outputs a byte to the file. I cannot find a read methes in the FileOutputStream class. But there is a read method ikn the InputStreamReader. The problem, is that the documentation I read said this class read function returns a char, by converting the bytes to a char. Will this change the data. How should I read the data back in.
code that saves the file and seems to work
boolean Save()
{
String FILENAME = "hello_file";
String string = "hello world!";
cDate mAppoitments[];
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE );
int i;
mAppoitments=cDates.GetUpperDates();
for(i=0;i<cDates.getMaxAmount();i++)
{
i=mAppoitments[i].getMonth();
fos.write( i );
开发者_StackOverflow社区 i=mAppoitments[i].getDay();
fos.write( i );
i=mAppoitments[i].getYear()-1900;
fos.write( i );
}
mAppoitments=cDates.GetLowerDates();
for(i=0;i<cDates.getMaxAmount();i++)
{
i=mAppoitments[i].getMonth();
fos.write( i );
i=mAppoitments[i].getDay();
fos.write( i );
i=mAppoitments[i].getYear()-1900;
fos.write( i );
}
fos.close();
}
// just catch all exceptions and return false
catch (Throwable t) {
return false;
}
return true;
}
Just open the file as a stream:
// open the file for reading
InputStream instream = openFileInput(FILENAME);
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
Than you can read it line by line
The rule I have is to use the same type of stream for reading and writing. So if you opened a file for writing using openFileOutput
, use openFileInput
to open the input stream for reading. since the method write(int)
writes one byte to the file, you may safely use the method read()
to read each byte and assign it to the variable.
BUT, there is a big problem in your loops - you modify i inside the loop, unrelated to the indexing:
i=mAppoitments[i].getMonth(); // now i might be assigned with 12
fos.write( i ); // you write 12
i=mAppoitments[i].getDay(); // now you look for mAppoitments[12].getDay()
....
Use a different variable to write those value to the file, don't modify i inside the loop. For example:
for(i=0;i<cDates.getMaxAmount();i++)
{
int j;
j=mAppoitments[i].getMonth();
fos.write( j );
j=mAppoitments[i].getDay();
fos.write( j );
j=mAppoitments[i].getYear()-1900;
fos.write( j );
}
If it's more comfortable for you, you can wrap the output stream in a PrinterWriter, and you can wrap the input steam reader in a BufferedReader. Then, you could write and read Strings.
I think you'll have some issues with using i
for an iterator and as your variable for storing what you're writing.
精彩评论