使用文件对数据进行存储、访问

来源:互联网 发布:香港电影推荐 知乎 编辑:程序博客网 时间:2024/05/01 18:49

使用文件对数据进行存储:

Activity提供了openFileOutput()方法可以把数据输出到文件中。

FileOutputStream outStream=this.openFileOutput("howay.txt",Context.MODE_PRIVATE);

outStream.write("数据存储".getBytes());

outStream.close();

这就是存储的整个过程,看起来蛮简单的吧。

 

关于那几种模式:

Context.MODE_PRIVATE:

为默认操作,代表该文件是私有数据,在该模式下,写入的内容会覆盖原来的内容

Context.MODE_APPEND:

检查是否存在,存在,就会追加到文件后面

MODE_WORD_WRITEABLE:

当前文件可以被其他应用写入

MODE_WORD_READABLE:

当前文件可以被其他应用读取

 

使用文件对数据进行访问:

Activity提供了openFileInput()方法对数据进行访问:

FileInputStream inStream=this.getContext.openFileInput("howay.txt");

Log.("FileTest",readInStream(inStream);

 

关于readInStream()这个方法:

public static String readInStream(FileInputStream inStream){

       try{

       ByteArrayOutputStream outStream=new ByteArrayOutputStream();

       byte[] buffer= new byte[1024];

       int length=-1;

       while((length=inStream.read(buffer))  != -1){

              outStream.write(buffer,0,length);

         }

             outStream.close();

             inStream.close();

              return outStream.toString();

      }catch(IOException e){

         Log.i("FileTest",e.getMessage());

    }

    return null;

}