当前位置: 移动技术网 > IT编程>移动开发>Android > Android编程之文件的读写实例详解

Android编程之文件的读写实例详解

2019年07月24日  | 移动技术网IT编程  | 我要评论

两女一 杯完整版,江山风雨情演员表,spica.s

本文实例分析了android编程之文件的读写方法。分享给大家供大家参考,具体如下:

android的文件读写与javase的文件读写相同,都是使用io流。而且android使用的正是javase的io流,下面我们通过一个练习来学习android的文件读写。

1.创建一个android工程

project name:file
    buildtarget:android2.2
    application name:文件读写
    package name:test.file
    create activity:dateactivity
    min sdk version:8

strings.xml文件内容:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
 <string name="app_name">数据保存</string> 
 <string name="file_name">文件名</string> 
 <string name="file_content">文件内容</string> 
 <string name="button_file_save">保存</string> 
 <string name="button_file_read">读取</string> 
 <string name="file_save_success">保存文件成功</string> 
 <string name="file_save_failed">保存文件失败</string> 
 <string name="file_read_failed">读取文件失败</string> 
</resources>

main.xml文件内容:

<?xml version="1.0" encoding="utf-8"?> 
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical" android:layout_width="fill_parent" 
  android:layout_height="fill_parent"> 
  <!-- 文件名 --> 
  <textview android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:text="@string/file_name" /> 
  <edittext android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:id="@+id/et_file_name" /> 
  <textview android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:text="@string/file_content" /> 
  <edittext android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:minlines="3" 
    android:id="@+id/et_file_content" /> 
  <relativelayout android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
    <button android:layout_width="wrap_content" 
      android:layout_height="wrap_content" android:text="@string/button_file_save" 
      android:id="@+id/bt_save" /> 
    <button android:layout_width="wrap_content" 
      android:layout_height="wrap_content" android:layout_torightof="@id/bt_save" 
      android:text="@string/button_file_read" android:id="@+id/bt_read" 
      android:layout_aligntop="@id/bt_save" 
      /> 
  </relativelayout> 
</linearlayout>

添加java代码

首先我们向工程中添加一个fileservice.java:其实就是用的java里面的文件操作。

package test.service; 
import java.io.bytearrayoutputstream; 
import java.io.file; 
import java.io.fileinputstream; 
import java.io.fileoutputstream; 
import android.content.context; 
import android.os.environment; 
public class fileservice { 
private context context; 
public fileservice(context context) { 
this.context = context; 
} 
public void savetosdcard(string filename, string content) throws exception{ 
if(environment.getexternalstoragestate().equals(environment.media_mounted)){ 
file file = new file(environment.getexternalstoragedirectory(), filename); 
fileoutputstream outstream = new fileoutputstream(file); 
outstream.write(content.getbytes()); 
outstream.close(); 
} 
} 
public void save(string filename, string content) throws exception{ 
fileoutputstream outstream = context.openfileoutput(filename, context.mode_private); 
outstream.write(content.getbytes()); 
outstream.close(); 
}

然后再向工程中添加filebuttononclickevent.java:

package test.event; 
import test.file.r; 
import test.service.fileservice; 
import android.app.activity; 
import android.util.log; 
import android.view.view; 
import android.view.view.onclicklistener; 
import android.widget.button; 
import android.widget.edittext; 
import android.widget.toast; 
public class filebuttononclickevent implements onclicklistener { 
 private activity activity; 
 // 通过fileservice读写文件 
 private fileservice fileservice; 
 // 打印信息用的标签 
 private static final string tag = "filebuttononclickevent"; 
 public filebuttononclickevent(activity activity) { 
  this.activity = activity; 
   this.fileservice = new fileservice(activity); 
 } 
public void onclick(view v) { 
button button = (button) v; 
  switch (button.getid()) { 
  case r.id.bt_save: 
    // 获取文件名 
    edittext etfilenames = (edittext) this.activity 
        .findviewbyid(r.id.et_file_name); 
    string filenames = etfilenames.gettext().tostring(); 
    // 获取文件内容 
    edittext etfilecons = (edittext) this.activity 
        .findviewbyid(r.id.et_file_content); 
    string filecontents = etfilecons.gettext().tostring(); 
    // 保存 
    try { 
      this.fileservice.save(filenames, filecontents); 
      // 在窗口中显示一个特效信息框 
      toast.maketext(this.activity, r.string.file_save_success,
         toast.length_long).show(); 
      log.i(tag, "save file success!"); 
    } catch (exception e) { 
      toast.maketext(this.activity, r.string.file_save_failed, 
         toast.length_long).show(); 
      log.e(tag, e.tostring()); 
    } 
    break; 
  case r.id.bt_read: 
    // 获取文件名 
    edittext etfilenamer = (edittext) this.activity 
        .findviewbyid(r.id.et_file_name); 
    string filenamer = etfilenamer.gettext().tostring(); 
    // 读取文件 
    try { 
      string fielcontentr = this.fileservice.readfile(filenamer); 
      edittext etfileconr = (edittext) this.activity 
         .findviewbyid(r.id.et_file_content); 
      etfileconr.settext(fielcontentr); 
      log.i(tag, "read file success!"); 
    } catch (exception e) { 
      toast.maketext(this.activity, r.string.file_read_failed, 
         toast.length_long).show(); 
      log.e(tag, e.tostring()); 
    } 
    break; 
  default: 
    break; 
  } 
} 
} 
public void saveappend(string filename, string content) throws exception{// ctrl+shift+y / x 
fileoutputstream outstream = context.openfileoutput(filename, context.mode_append); 
outstream.write(content.getbytes()); 
outstream.close(); 
} 
public void savereadable(string filename, string content) throws exception{// ctrl+shift+y / x 
fileoutputstream outstream = context.openfileoutput(filename, context.mode_world_readable); 
outstream.write(content.getbytes()); 
outstream.close(); 
} 
public void savewriteable(string filename, string content) throws exception{// ctrl+shift+y / x 
fileoutputstream outstream = context.openfileoutput(filename, context.mode_world_writeable); 
outstream.write(content.getbytes()); 
outstream.close(); 
} 
public void saverw(string filename, string content) throws exception{ 
fileoutputstream outstream = context.openfileoutput(filename, 
context.mode_world_readable+ context.mode_world_writeable); 
outstream.write(content.getbytes()); 
outstream.close(); 
} 
public void saveprw(string filename, string content) throws exception{ 
fileoutputstream outstream = context.openfileoutput(filename, 
context.mode_world_readable+ context.mode_world_writeable+context.mode_append);
outstream.write(content.getbytes()); 
outstream.close(); 
} 
public string readfile(string filename) throws exception{ 
fileinputstream instream = context.openfileinput(filename); 
byte[] data = readdata(instream); 
return new string(data); 
} 
private byte[] readdata(fileinputstream instream) throws exception{ 
bytearrayoutputstream outstream = new bytearrayoutputstream(); 
byte[] buffer = new byte[1024]; 
int len = 0; 
while( (len = instream.read(buffer))!= -1){ 
outstream.write(buffer, 0, len); 
}
outstream.close();
instream.close();
return outstream.tobytearray();
}
}

最后就是我们的主activity:dateactivity

package test.file; 
import test.event.filebuttononclickevent; 
import android.app.activity; 
import android.os.bundle; 
import android.widget.button; 
public class dateactivity extends activity { 
 /** called when the activity is first created. */ 
 @override 
 public void oncreate(bundle savedinstancestate) { 
  super.oncreate(savedinstancestate); 
  setcontentview(r.layout.main); 
  // 获取所有按钮 
  button buttonread = (button) this.findviewbyid(r.id.bt_read); 
  button buttonsave = (button) this.findviewbyid(r.id.bt_save); 
  // 为按钮添加事件 
  filebuttononclickevent filebtonclickeve = new filebuttononclickevent(this); 
  buttonread.setonclicklistener(filebtonclickeve); 
  buttonsave.setonclicklistener(filebtonclickeve); 
 }
}

我们的dateactivity.java的可读性是否很好?当然!以后继续改进。但我们的fileservice并未使用接口,在javaee都使用接口来开发,这样可以实现解耦。由于在android是手机操作系统平台,如果我们开设的类比较多,会占用系统资源,从而导致系统变慢。所以,尽量的减少接口或类的定义,但也要尽量的做到程序的可读性要好。所以我们也可以把dataactivity和filebuttononclickevent合并。

启动模拟器,部署我们的程序。输入文件名和文件内容,点击保存。文件被保存在android的什么位置?我们知道android是基于linux实现的。所以它的根目录是"/",我们的文件被保存在"/data/data/你的包名.file/files"目录下。

我们也可以通过菜单windows->show view->other...->android->file explorer,打开 file explorer面板。通过它可以查看android的目录结构:

data:应用数据,我们保存的文件在/data/data/packagename/files。

sdcard:现在的手机一般都可以外插一个sd卡,这个目录就是sdcard的目录。操作此目录时需要在主配置文件中注册操作权限。

system:android操作系统的文件,我们不要修改。
我们可以点击 file explorer右上角的"软盘向左箭头"图标,导出文件。

openfileoutput()方法的第一参数用于指定文件名称,不能包含路径分隔符"/" ,如果文件不存在,android 会自动创建它。创建的文件保存在/data/data/<package name>/files目录,
openfileoutput()方法的第二参数用于指定操作模式,有四种模式,分别为:

context.mode_private  = 0
context.mode_append  = 32768
context.mode_world_readable = 1
context.mode_world_writeable = 2

context.mode_private:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用context.mode_append
context.mode_append:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。该模式也是私有数据,只能被应用本身访问。
context.mode_world_readable和context.mode_world_writeable用来控制其他应用是否有权限读写该文件。
mode_world_readable:表示当前文件可以被其他应用读取;mode_world_writeable:表示当前文件可以被其他应用写入。

可以使用+连接这些权限 :

如果希望文件被其他应用读和写,可以传入:

复制代码 代码如下:
openfileoutput("itcast.txt", context.mode_world_readable + context.mode_world_writeable);

如果希望文件被其他应用读和写还要是追加内容的,可以传入:
复制代码 代码如下:
openfileoutput("itcast.txt", context.mode_world_readable + context.mode_world_writeable+ context.mode_append);

android有一套自己的安全模型,当应用程序(.apk)在安装时系统就会分配给他一个userid,当该应用要去访问其他资源比如文件的时候,就需要userid匹配。默认情况下,任何应用创建的文件,sharedpreferences,数据库都应该是私有的(位于/data/data/<package name>/files),其他程序无法访问。除非在创建时指定了context.mode_world_readable或者context.mode_world_writeable ,只有这样其他程序才能正确访问。

与outputstream一样,可以通过context对象调用fileinputstream openfileinput(string name),来打开位于当前应用程序私有文件目录下文件名为name的文件的inputstream。若文件不存在时会直接抛出filenotfoundexception异常。

另外,当应用程序需要从项目工程目录assets/下的读出数据时,可以通过调用context对象的方式打开文件名为name文件爱你的inputstream:inputstream in=this.getassets.open(name);。

context对象还可以通过调用filelist()方法来获得私有文件目录下所有的文件名组成的字符串数组,调用deletefile(string name)来删除文件名为name的文件。

activity还提供了getcachedir()和getfilesdir()方法:

getcachedir()方法用于获取/data/data/<package name>/cache目录(一些临时文件可以放在缓存目录用完了就删了)
getfilesdir()方法用于获取/data/data/<package name>/files目录

其他程序获取文件路径的方法

1.绝对路径:/data/data/packagename/files/filename;

2.context:  context.getfilesdir()+"/filename";

缓存目录:/data/data/packagename/cache或getcachedir();

如果文件过大就不能存放在手机的文件目录,需要存储到sdcard上。

使用activity的openfileoutput()方法保存文件,文件是存放在手机空间上,一般手机的存储空间不是很大,存放些小文件还行,如果要存放像视频这样的大文件,是不可行的。对于像视频这样的大文件,我们可以把它存放在sdcard。 sdcard是干什么的?你可以把它看作是移动硬盘或u盘。

在模拟器中使用sdcard,你需要先创建一张sdcard卡(当然不是真的sdcard,只是镜像文件)。创建sdcard可以在eclipse创建模拟器时随同创建,也可以使用dos命令进行创建,如下:

在dos窗口中进入android sdk安装路径的tools目录,输入以下命令创建一张容量为2g的sdcard,文件后缀可以随便取,建议使用.img:
mksdcard 2048m d:\androidtool\sdcard.img

在程序中访问sdcard,你需要申请访问sdcard的权限。

在androidmanifest.xml中加入访问sdcard的权限如下:

<!-- 在sdcard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.mount_unmount_filesystems"/>
<!-- 往sdcard写入数据权限 -->
<uses-permission android:name="android.permission.write_external_storage"/>

存放在sdcard的文件可以被任何应用访问到的!

sdcard目录:/sdcard/或environment.getexternalstoragedirectory()
使用sdcard目录前,需要判断是否有sdcard:environment.getexternalstoragestate()。操作此目录时需要在主配置文件中注册操作权限。

如果environment.getexternalstoragestate()等于 environment.media_mounted  表示 sdcard存在并且可以进行读写
file sdcarddir = environment.getexternalstoragedirectory();//获取sdcard目录
等价于 file sdcarddir = new file("/sdcard"); //获取sdcard目录

要往sdcard存放文件,程序必须先判断手机是否装有sdcard,并且可以进行读写。

注意:访问sdcard必须在androidmanifest.xml中加入访问sdcard的权限

if(environment.getexternalstoragestate().equals(environment.media_mounted)){
   file sdcarddir = environment.getexternalstoragedirectory();//获取sdcard目录
   file savefile = new file(sdcarddir, "itcast.txt");
fileoutputstream outstream = new fileoutputstream(savefile);
outstream.write("写入的内容".getbytes());
outstream.close();
}

environment.getexternalstoragestate()方法用于获取sdcard的状态,如果手机装有sdcard,并且可以进行读写,那么方法返回的状态等于environment.media_mounted。
environment.getexternalstoragedirectory()方法用于获取sdcard的目录,当然要获取sdcard的目录,你也可以这样写:

file sdcarddir = new file("/sdcard"); //获取sdcard目录
file savefile = new file(sdcarddir, "itcast.txt"); 
//上面两句代码可以合成一句: file savefile = new file("/sdcard/itcast.txt");
//上面两句代码可以合成一句: file savefile = new file(environment.getexternalstoragedirectory(), "itcast.txt");
fileoutputstream outstream = new fileoutputstream(savefile);
outstream.write("写入的内容".getbytes());
outstream.close();

希望本文所述对大家android程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网