Android读写文件

来源:互联网 发布:淘宝学院官网 编辑:程序博客网 时间:2024/06/11 07:31

[转]Android读写文件

本文转自:http://blog.sina.com.cn/s/blog_4d25c9870100qpax.html

 

一、       resource中的raw文件夹中获取文件并读取数据(资源文件只能读不能写)

String res = ""; 

try{ 

InputStream in = getResources().openRawResource(R.raw.bbi); 

//\Test\res\raw\bbi.txt,

   int length = in.available();       

   byte [] buffer = new byte[length];        

   in.read(buffer);         

   //res = EncodingUtils.getString(buffer, "UTF-8");

   //res = EncodingUtils.getString(buffer, "UNICODE"); 

   res = EncodingUtils.getString(buffer, "BIG5"); 

   //bbi.txt的编码类型选择合适的编码,如果不调整会乱码

   in.close();            

   }catch(Exception e){ 

      e.printStackTrace();         

   } 

myTextView.setText(res);//把得到的内容显示在TextView

 

二、       asset中获取文件并读取数据(资源文件只能读不能写)

String fileName = "yan.txt"; //文件名字

String res=""; 

try{ 

   InputStream in = getResources().getAssets().open(fileName);

   // \Test\assets\yan.txt这里有这样的文件存在

   int length = in.available();         

byte [] buffer = new byte[length];        

in.read(buffer);            

res = EncodingUtils.getString(buffer, "UTF-8");     

}catch(Exception e){ 

      e.printStackTrace();         

   }

 

三、       sdcard中去读文件,首先要把文件通过\android-sdk-windows\tools\adb.exe把本地计算机上的文件copysdcard上去,adb.exe push e:/Y.txt /sdcard/, 不可以用adb.exe push e:\Y.txt \sdcard\ 同样: 把仿真器上的文件copy到本地计算机上用: adb pull ./data/data/com.tt/files/Test.txt e:/

 

String fileName = "/sdcard/Y.txt";

//也可以用String fileName = "mnt/sdcard/Y.txt";

String res="";     

try{ 

FileInputStream fin = new FileInputStream(fileName);

//FileInputStream fin = openFileInput(fileName);  

//用这个就不行了,必须用FileInputStream

    int length = fin.available(); 

    byte [] buffer = new byte[length]; 

    fin.read(buffer);     

    res = EncodingUtils.getString(buffer, "UTF-8"); 

    fin.close();     

    }catch(Exception e){ 

           e.printStackTrace(); 

} 

myTextView.setText(res);

 

四、       写文件, 一般写在\data\data\com.test\files\里面,打开DDMS查看file explorer是可以看到仿真器文件存放目录的结构的

   String fileName = "TEST.txt";

   String message = "FFFFFFF11111FFFFF" ;

writeFileData(fileName, message);

  

   public voidwriteFileData(String fileName,String message){ 

       try{ 

        FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);

        byte [] bytes = message.getBytes(); 

        fout.write(bytes); 

         fout.close(); 

        } 

       catch(Exception e){ 

        e.printStackTrace(); 

       } 

   }    

 

五、       写, data/data/目录(相当AP工作目录)上的文件,openFileOutput

   //写文件在./data/data/com.tt/files/下面

   public voidwriteFileData(String fileName,String message){ 

       try{ 

        FileOutputStream fout =openFileOutput(fileName, MODE_PRIVATE);

        byte [] bytes = message.getBytes(); 

        fout.write(bytes); 

         fout.close(); 

        } 

       catch(Exception e){ 

        e.printStackTrace(); 

       } 

   }

//-------------------------------------------------------

//读文件在./data/data/com.tt/files/下面

   public String readFileData(String fileName){ 

        String res=""; 

        try{ 

         FileInputStream fin = openFileInput(fileName); 

         int length = fin.available(); 

         byte [] buffer = new byte[length]; 

         fin.read(buffer);     

         res = EncodingUtils.getString(buffer, "UTF-8"); 

         fin.close();     

        } 

        catch(Exception e){ 

         e.printStackTrace(); 

        } 

        return res; 

    }   

六、       写, sdcard目录上的文件,要用FileOutputStream 不能用openFileOutput

 

    //写在/mnt/sdcard/目录下面的文件

   public voidwriteFileSdcard(String fileName,String message){ 

       try{ 

        //FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);

       FileOutputStream fout = newFileOutputStream(fileName);

        byte [] bytes = message.getBytes(); 

        fout.write(bytes); 

         fout.close(); 

        } 

       catch(Exception e){ 

        e.printStackTrace(); 

       } 

   }

  

   //读在/mnt/sdcard/目录下面的文件

   public String readFileSdcard(String fileName){

        String res=""; 

        try{ 

         FileInputStream fin = new FileInputStream(fileName); 

         int length = fin.available(); 

         byte [] buffer = new byte[length]; 

         fin.read(buffer);     

         res = EncodingUtils.getString(buffer, "UTF-8"); 

         fin.close();     

        } 

        catch(Exception e){ 

         e.printStackTrace(); 

        } 

        return res; 

   }

 

注: openFileOutput是在raw里编译过的,FileOutputStream是任何文件都可以

 

参考:http://dev.10086.cn/cmdn/wiki/index.php?doc-view-6017.html

 

分类: Android-app
绿色通道: 好文要顶 关注我 收藏该文与我联系 
freeliver54
关注 - 0
粉丝 - 233
+加关注
5
0
(请您对文章做出评价)
« 上一篇:[转]全国公共英语PETS三级作文经典辅导
» 下一篇:[转]23种经典设计模式的java实现_5_职责链模式

posted on 2011-09-16 16:31 freeliver54 阅读(31558) 评论(6) 编辑 收藏

评论

#1楼[楼主]   回复引用

Android读写文件正确实行方法介绍
http://www.ehuait.com/skill/android/2011-09-08/1445.html
众所周知Android有一套自己的安全模型, 具体可参见Android开发文档。当应用程序(.apk)在安装时就会分配一个userid,当该应用要去访问其他资源比如文件的时候,就需要userid匹配。默认情况下 ,任何应用创建的文件,数据库, sharedpreferences都应该是私有的(位于/data/data/your_project/files/),其余程序无法访问。除非在创建时指明是MODE_WORLD_READABLE 或者 MODE_WORLD_WRITEABLE,只要这样其余程序才能正确访问。 

因为有这种Android读写文件的方法在安全上有所保障,进程打开文件时Android要求检查进程的user id。所以不能直接用java的api来打开,因为java的io函数没有提这个机制 。

无法用java的api直接打开程序私有的数据 ,默认路径为/data/data/your_project/files/

1.FileReader file = new FileReader("Android.txt"); 这里特别强调私有数据!言外之意是如果某个文件或者数据不是程序私有的,既访问它时无须经过Android的权限检查,那么还是可以用java的io api来直接访问的。所谓的非私有数据是只放在sdcard上的文件或者数据,

可以用java的io api来直接打开sdcard上文件。 

1.FileReader file = new FileReader("/sdcard/Android.txt"); 如果要打开程序自己私有的文件和数据,那必须使用Activity提供openFileOutput和openFileInput方法。

创建程序私有的文件,由于权限方面的要求,必须使用activity提供的Android读写文件方法 

1.FileOutputStream os = this.openFileOutput("Android.txt", MODE_PRIVATE); 
2.OutputStreamWriter outWriter = new OutputStreamWriter (os); 
读取程序私有的文件,由于权限方面的要求,必须使用activity提供的方法 
1.FileInputStream os =this.openFileInput("Android.txt"); 
2.InputStreamReader inReader = new InputStreamReader(os); Android读写文件的相关操作就为大家介绍到这里。
支持(0)反对(0)
2011-11-01 15:23 | freeliver54  

#2楼[楼主]   回复引用

http://www.eoeandroid.com/thread-72823-1-1.html
考虑到SD卡可能没有被mount,或者其他各种情况,操作SD卡上的文件总需要各种状态的判断。主要是使用Environment类里的一些接口进行判断:

Java代码:

01.private void writeFileToSD() {

02.String sdStatus = Environment.getExternalStorageState();

03.if(!sdStatus.equals(Environment.MEDIA_MOUNTED)) {

04.Log.d("TestFile", "SD card is not avaiable/writeable right now.");

05.return;

06.}

07.try {

08.String pathName="/sdcard/test/";

09.String fileName="file.txt";

10.File path = new File(pathName);

11.File file = new File(pathName + fileName);

12.if( !path.exists()) {

13.Log.d("TestFile", "Create the path:" + pathName);

14.path.mkdir();

15.}

16.if( !file.exists()) {

17.Log.d("TestFile", "Create the file:" + fileName);

18.file.createNewFile();

19.}

20.FileOutputStream stream = new FileOutputStream(file);

21.String s = "this is a test string writing to file.";

22.byte[] buf = s.getBytes();

23.stream.write(buf);

24.stream.close();

25.} catch(Exception e) {

26.Log.e("TestFile", "Error on writeFilToSD.");

27.e.printStackTrace();

28.}

29.}
复制代码
需要加入权限:

Java代码:
01.< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
复制代码
看文档说,可以使用Context.getExternalFilesDir来取得一个特殊的文件夹,该文件夹对USER不可见,最重要的是:当系统卸载该程序时,会自动删除该目录下的文件。  如果不需要往SD卡上写文件,可以直接用以下简单代码:

Java代码:

01.private void writeFile() {

02.try {

03.FileOutputStream stream = openFileOutput("testfile.txt", Context.MODE_WORLD_WRITEABLE);

04.String s = "this is a test string writing to file.";

05.byte[] buf = s.getBytes();

06.stream.write(buf);

07.stream.close();

08.}

09.catch (FileNotFoundException e) {

10.Log.d("TestFile", "File not found.");

11.}

12.catch (IOException e) {

13.Log.d("TestFile", "File write error.");

14.

15.}

16.

17.}
复制代码
  该文件会被放置于data/data/your_app_package_name/files下。  值得注意的是,我们可以在程序运行期间动态检查SD卡是否可用。大致就是通过注册BroadcastReceiver实现,这个官方文档里有提到:

Java代码:

01.void startWatchingExternalStorage() {

02.mExternalStorageReceiver = new BroadcastReceiver(){

03.

04.@Override

05.public void onReceive(Context context, Intent intent) {

06.Log.i("test", "Storage: " + intent.getData());

07.updateExternalStorageState();

08.}

09.

10.};

11.

12.IntentFilter filter = new IntentFilter();

13.filter.addAction(Intent.ACTION_MEDIA_MOUNTED);

14.filter.addAction(Intent.ACTION_MEDIA_REMOVED);

15.registerReceiver(mExternalStorageReceiver, filter);

16.updateExternalStorageState();

17.

18.}
支持(0)反对(0)
2011-11-03 09:42 | freeliver54  

#3楼[楼主]   回复引用

android工程根目录下文件的获取[问题点数:60分,结帖人:csuhanyong]
http://topic.csdn.net/u/20101118/17/8a731683-0234-4cac-be75-fb13b868f59f.html

我建了个abc.xml文件放在android工程的根目录下,如果在普通Java工程的话我用 File f = new File(abc.xml)就可以得到;但是在android环境下 会自动把这个路径变为 “/abc.xml”;然后报“ 11-18 08:58:43.572: WARN/System.err(19260): java.io.FileNotFoundException: /systemapps.xml (No such file or directory)”异常,可能是编译路径与以前不一样导致。
那有什么办法可以读取这个xml文件呢?

---------------

获取文件路径的方法

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

2.context:context.getFilesDir()+”/filename”;

缓存目录:/data/data/packagename/Cache或getCacheDir();

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

SDCard目录:/sdcard/或Environment.getExternalStorageDirectory()

使用SDCard目录前,需要判断是否有sdcard:Environment.getExternalStorageState()。操作此目录时需要在主配置文件中注册操作权限。
http://hi.baidu.com/garylijs/blog/item/afaa0dedeef215dbb31cb1d4.html

----------------------

android不支持读取与工程直接子级的文件。解决办法是:
在res文件夹下新建raw文件夹,然后将abc.xml复制到raw文件夹下。

读取代码:

Java code
InputStream input = getResources().openRawResource(R.raw.abc);
BufferedReader read = new BufferedReader(new InputStreamReader(input));
String line = "";
while((line=read.readLine()) != null){
System.out.println(line);
}


-----------------

或者
res文件夹下新建raw文件夹,然后将abc.xml复制到raw文件夹下
Java codeInputStream in = context.openFileInput("abc.xml");
支持(0)反对(0)
2011-11-03 09:45 | freeliver54  

#4楼[楼主]   回复引用

//Context.getExternalFilesDir
String[] logFiles = this.getFilesDir().list();
支持(0)反对(0)
2011-11-03 16:15 | freeliver54  

#5楼   回复引用

很好,学习了!
支持(0)反对(0)
2012-02-27 20:37 | 雨焰  

#6楼[楼主]   回复引用

http://blog.csdn.net/svrsimon/article/details/7079320
Android 获取assets的绝对路径 
第一种方法:
String path = "file:///android_asset/文件名";

第二种方法:
InputStream abpath = getClass().getResourceAsStream("/assets/文件名");


若要想要转换成String类型

String path = new String(InputStreamToByte(abpath ));


private byte[] InputStreamToByte(InputStream is) throws IOException {
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1) {
bytestream.write(ch);
}
byte imgdata[] = bytestream.toByteArray();
bytestream.close();
return imgdata;
}

原创粉丝点击