保存后我无法弄清楚如何读取数据

时间:2011-05-06 22:03:40

标签: android file

问题是我正在使用FileOutputStream类的write方法。我读过的文档说这会向文件输出一个字节。我在FileOutputStream类中找不到read methes。 但是有一个读取方法ikn InputStreamReader。问题是,我读过的文档说这个类读取函数通过将字节转换为char来返回一个char。这会改变数据吗?我应该如何阅读数据。

保存文件并且似乎正常工作的代码

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  );
          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;
  }

4 个答案:

答案 0 :(得分:1)

只需将文件作为流打开:

// open the file for reading
InputStream instream = openFileInput(FILENAME);
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);

你可以逐行阅读

答案 1 :(得分:1)

我的规则是使用相同类型的流进行读写。因此,如果您使用openFileOutput打开要写入的文件,请使用openFileInput打开输入流进行读取。由于方法write(int)将一个字节写入文件,因此您可以安全地使用方法read()来读取每个字节并将其分配给变量。

但是,你的循环中存在一个大问题 - 你在循环中修改我,与索引无关:

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

使用不同的变量将这些值写入文件,不要在循环内修改i。例如:

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  );            
  }

答案 2 :(得分:0)

如果您觉得更舒服,可以将输出流包装在PrinterWriter中,然后将输入蒸汽读取器包装在BufferedReader中。然后,你可以写和读字符串。

答案 3 :(得分:0)

我认为你在使用i作为迭代器时会遇到一些问题,而作为存储你正在编写的内容的变量会有一些问题。