`
kanwoerzi
  • 浏览: 1648029 次
文章分类
社区版块
存档分类
最新评论

android中读写文件

 
阅读更多
众所周知Android有一套自己的安全模型,具体可参见Android开发文档。当应用程序(.apk)在安装时就会分配一个userid,
当该应用要去访问其他资源比如文件的时候,就需要
userid匹配
默认情况下,任何应用程序创建的文件,数据库,sharedpreferences都应该是私有的(位于/data/data/your_project/files/),
程序私有的数据的默认路径为/data/data/your_project/files/;
其余程序无法访问。除非在创建时指明是
MODE_WORLD_READABLE或者MODE_WORLD_WRITEABLE,只有这样其余程序才能正确访问。
因为Android有这种为读写文件而提供的安全保障体系(进程打开程序私人文件时,Android要求检查进程的userid);
所以我们不能直接用java的api来打开程序的私有文件。
比如:
1.FileReaderfile=newFileReader("Android.txt");
上面的代码将不能成功执行。
这里特别强调私有数据言外之意是如果某个文件或者数据不是程序私有的,既访问它时无须经过Android的权限检查,那么还是可以用java的ioapi来直接访问的。所谓的非私有数据是只放在sdcard上的文件或者数据,
可以用java的ioapi来直接打开sdcard上文件。

1.FileReaderfile=newFileReader("/sdcard/Android.txt");
如果要打开程序自己私有的文件和数据,那必须使用Activity提供openFileOutputopenFileInput方法。
创建程序私有的文件,由于权限方面的要求,必须使用activity提供的文件操作方法

1.FileOutputStreamos=this.openFileOutput("Android.txt",MODE_PRIVATE);
2.OutputStreamWriteroutWriter=newOutputStreamWriter(os);

读取程序私有的文件,由于权限方面的要求,必须使用activity提供的文件操作方法
1.FileInputStreamos=this.openFileInput("Android.txt");
2.InputStreamReaderinReader=newInputStreamReader(os);
提速文件读写
其原理就是读的时候,先把文件的一些数据读到缓冲中。
这样的好处是如果读的内容已经在缓冲中,就读缓冲的数据。
如果没有,就让缓冲先从文件读取数据,然后再从缓冲读数据。

写操作与操作同理.
这样的好处是减少对文件的操作次数,从而达到提高性能的目的。
坏处是要额外的内存来做缓冲区.

对于FileInputStream和FileOutputStream用下面的方式。
BufferedInputStreambuf=newBufferedInputStream(newFileInputStream("file.java"));
BufferedOutputStreambuf=newBufferedOutputStream(newFileOutputStream("file.java"));

对于FileReader和FileReader用下面的方式
BufferedReaderbuf=newBufferedReader(newFileReader("file.java"));
BufferedWriterbuf=newBufferedWriter(newFileWriter("file.java"));

对于写操作最后最好加上flush().
实例1:
voidwrite2File()
{
Stringcontent="hello:"+System.currentTimeMillis();
FileOutputStreamos=null;
StringfileName="hubin.txt";
intmode=Context.MODE_WORLD_WRITEABLE|Context.MODE_WORLD_READABLE;
try{
os=openFileOutput(fileName,mode);
os.write(content.getBytes());

/*OutputStreamWriteroutWriter=newOutputStreamWriter(os);
outWriter.write(content);*/

Log.i(tag,"write:"+content);
}catch(FileNotFoundExceptione)
{
Log.e(tag,"createFile:",e);
}
catch(IOExceptione)
{
Log.e(tag,"writefile",e);
}
finally
{
if(os!=null)
{
try{
os.flush();
os.close();

}catch(IOExceptione)
{
Log.e(tag,"closefile",e);
}
}
}

}
voidreadFromFile()
{
Stringcontent;
FileInputStreamis=null;
StringfileName="hubin.txt";
try{
is=openFileInput(fileName);
bytebuffer[]=newbyte[is.available()];
is.read(buffer);
content=newString(buffer);

Log.i(tag,"read:"+content);
//InputStreamReaderinReader=newInputStreamReader(is);
}catch(FileNotFoundExceptione)
{
Log.e(tag,"createFile:",e);
}
catch(IOExceptione)
{
Log.e(tag,"writefile",e);
}
finally
{
if(is!=null)
{
try{
is.close();
}catch(IOExceptione)
{
Log.e(tag,"closefile",e);
}
}
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics