file(内部存储与外部存储)

android的文件编程与JAVA下的文件编程无太多区别,注意的是几点。

1、android的文件系统分为内部和外部两种,内部是指系统的指定目录:/data/data/Activity所在的包/files,外部通常是SD卡,如下代码:

textview.setText(getApplicationContext().getFilesDir() 
                + ":      " + Environment.getExternalStorageDirectory().getAbsolutePath());

执行结果分别为:/data/data/com.example.data02/files  以及mnt/sdcard。

2、对内部存储系统操作,Android提供了openFileOutput和openFileInput,代码如下:

        FileOutputStream outputStream;
        try {
            /*         MODE_PRIVATE 私有(只能创建它的应用访问) 重复写入时会文件覆盖 
            *          MODE_APPEND  私有   重复写入时会在文件的末尾进行追加,而不是覆盖掉原来的文件 
            *          MODE_WORLD_READABLE 公用  可读 
            *          MODE_WORLD_WRITEABLE 公用 可读写*/
            outputStream = openFileOutput("test.txt",  
                    Activity.MODE_PRIVATE);
            outputStream.write(textview.getText().toString().getBytes());  
            outputStream.flush();  
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
        try {  
            FileInputStream in = this.openFileInput("test.txt"); 
            byte[] buffer = new byte[1024];  
            in.read(buffer);  
            String str = EncodingUtils.getString(buffer, "UTF-8");  
            textview1.setText(str.toString());  
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  

3、针对SD卡的文件系统操作,与JAVA文件编写一样,唯一要注意的是增加权限:

    <span style="white-space:pre">  </span><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
   <span style="white-space:pre">   </span><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

代码实例如下:

        File sdcDir = Environment.getExternalStorageDirectory();  
        File file = new File(sdcDir,"info.txt");  
        
        try {
            FileOutputStream output = new FileOutputStream(file);
            output.write(textview.getText().toString().getBytes());  
            output.flush();  
            output.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
        try {  
            FileInputStream inn = new FileInputStream(file);   
            byte[] buffer = new byte[1024];  
            inn.read(buffer);  
            String str = EncodingUtils.getString(buffer, "UTF-8");  
            textview2.setText(str.toString());  
            inn.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 

 

posted @ 2013-01-26 19:39  Fredric_2013  阅读(367)  评论(0编辑  收藏  举报