`
wangbobe
  • 浏览: 4834 次
社区版块
存档分类

Android之怎么操作文件(读写以及保存到sdcard)

阅读更多

步骤如下:

 

一、介绍:

       此主要是介绍怎么把文件写入到手机存储上、怎么从手机存储上读取文件内容以及怎么把文件写到SDCard

二、新建一个android工程——FileOperate

       目录如下:

三、清单列表AndroidManifest.xml的配置为:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.files"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        
        <!--单元测试 加这句-->
        <uses-library android:name="android.test.runner" />
        
        <activity
            android:name=".FileActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
   <!-- 往SDCard的创建与删除文件权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <!-- 往SDCard写入数据权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
    
    <!--单元测试加这句,其中android:targetPackage为当前应用的包名
    android:targetPackage 目标包是指单元测试的类的上面包和manifest的 
    package="com.example.main" 保持一致     
          这样就决定了你建立测试类的时候也必须在这个包下面
    -->
 <instrumentation android:name="android.test.InstrumentationTestRunner"
 android:targetPackage="com.example.files"
 android:label="Test for my app"/>
    
    
</manifest>

 

四、FileActivity.java源码:

package com.example.files;

import java.io.FileNotFoundException;
import java.io.IOException;

import com.example.service.FileService;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class FileActivity extends Activity {
 
 EditText fileName ;
 EditText fileContent;
 Button fileSave;
 OnClickListener fileSaveListener;
 OnClickListener fileSaveSDListener;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        fileSaveListener = new OnClickListener(){

   @Override
   public void onClick(View v) {
    //setTitle("123");
    //Toast.makeText(FileActivity.this, "123", Toast.LENGTH_LONG).show();
    String fileNameStr = fileName.getText().toString();
    String fileContentStr = fileContent.getText().toString();
    
    FileService fileService = new FileService(getApplicationContext());
    try {
     fileService.save(fileNameStr,fileContentStr);
     Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
    } catch (FileNotFoundException e) {
     Toast.makeText(getApplicationContext(), R.string.failure, Toast.LENGTH_LONG).show();
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    
    
   }
         
        };
        
        fileSaveSDListener = new OnClickListener(){

   @Override
   public void onClick(View v) {
    //setTitle("123");
    //Toast.makeText(FileActivity.this, "123", Toast.LENGTH_LONG).show();
    String fileNameStr = fileName.getText().toString();
    String fileContentStr = fileContent.getText().toString();
    
    FileService fileService = new FileService(getApplicationContext());
    try {
     //判断SDCard是否存在并且可以读写
     if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
      fileService.saveToSD(fileNameStr,fileContentStr);
      Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
     } 
     else
     {
      Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
     }
     
    } catch (FileNotFoundException e) {
     Toast.makeText(getApplicationContext(), R.string.sdcardfail, Toast.LENGTH_LONG).show();
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    
    
   }
         
        };
        
        Button fileSave = (Button) this.findViewById(R.id.fileSave);
        fileSave.setOnClickListener(fileSaveListener);
        
        Button fileSaveSD = (Button) this.findViewById(R.id.fileSaveSD);
        fileSaveSD.setOnClickListener(fileSaveSDListener);
        
        fileName = (EditText) this.findViewById(R.id.fileName);
        fileContent = (EditText) this.findViewById(R.id.fileContent);
        
        
        
    }
}

五、FileService.java源码:

package com.example.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;

public class FileService {
 
 private Context context;

 public FileService(Context context) {
  super();
  this.context = context;
 }
 /**
  * 写入文件到SD卡
  * @throws IOException 
  */
 public void saveToSD(String fileNameStr, String fileContentStr) throws IOException{
  
  //备注:Java File类能够创建文件或者文件夹,但是不能两个一起创建
  File file = new File("/mnt/sdcard/myfiles");
//  if(!file.exists())
//  {
//   file.mkdirs();
//  }
//   File sd=Environment.getExternalStorageDirectory(); 
//      String path=sd.getPath()+"/myfiles"; 
//      File file=new File(path); 
//      if(file.exists()){ 
//          file.delete(); 
//      }
      if(!file.exists()){
       file.mkdir();
      }
      File file1 = new File(file, fileNameStr);


  FileOutputStream fos = new FileOutputStream(file1);
  fos.write(fileContentStr.getBytes());
  fos.close();
 }

 /**
  * 保存文件到手机
  * @param fileNameStr 文件名
  * @param fileContentStr 文件内容
  * @throws IOException 
  */
 public void save(String fileNameStr, String fileContentStr) throws IOException {
  //私有操作模式:创建出来的文件只能被本应用访问,其它应用无法访问该文件,另外采用私有操作模式创建的文件,写入文件中的内容会覆盖原文件的内容
  FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE_PRIVATE);
  fos.write(fileContentStr.getBytes());
  fos.close();
 }
 
 public void saveAppend(String fileNameStr, String fileContentStr) throws IOException {
  //追加操作模式:不覆盖源文件,但是同样其它应用无法访问该文件
  FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE_APPEND);
  fos.write(fileContentStr.getBytes());
  fos.close();
 }
 
 public void saveReadable(String fileNameStr, String fileContentStr) throws IOException {
  //读取操作模式:可以被其它应用读取,但不能写入
  FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE_WORLD_READABLE);
  fos.write(fileContentStr.getBytes());
  fos.close();
 }
 
 public void saveWriteable(String fileNameStr, String fileContentStr) throws IOException {
  //写入操作模式:可以被其它应用写入,但不能读取
  FileOutputStream fos = context.openFileOutput(fileNameStr, context.MODE_WORLD_WRITEABLE);
  fos.write(fileContentStr.getBytes());
  fos.close();
 }
 
 public void saveReadWriteable(String fileNameStr, String fileContentStr) throws IOException {
  //读写操作模式:可以被其它应用读写
  FileOutputStream fos = context.openFileOutput(fileNameStr, 
    context.MODE_WORLD_READABLE+context.MODE_WORLD_WRITEABLE);
  fos.write(fileContentStr.getBytes());
  fos.close();
 }
 
 
 /**
  * 读取文件内容
  * @param fileNamestr 文件名
  * @return
  * @throws IOException
  */
 public String read(String fileNamestr) throws IOException
 {
  FileInputStream fis = context.openFileInput(fileNamestr);
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  while((len = fis.read(buffer)) != -1){
   bos.write(buffer,0,len);
  }
  byte[] data = bos.toByteArray();
  
  
  return new String(data);
 }

}

六、FileServiceTest.java源码:

package com.junit.test;

import com.example.service.FileService;

import android.test.AndroidTestCase;
import android.util.Log;

public class FileServiceTest extends AndroidTestCase {
     /**
      * 测试私有模式的读取
      * @throws Exception
      */
        public void testRead() throws Exception{
         FileService fileService = new FileService(this.getContext());
         String fileContext = fileService.read("fileSave.txt");
         Log.i("FileRead", fileContext);
        }
        /**
         * 测试追加模式的写入
         * @throws Exception
         */
        public void testSaveAppend() throws Exception{
         FileService fileService = new FileService(this.getContext());
         fileService.saveAppend("fileAppendSave.txt", "你好");
        }
        /**
         * 测试读取模式的读取
         * @throws Exception
         */
        public void testSaveReadable() throws Exception{
         FileService fileService = new FileService(this.getContext());
         fileService.saveReadable("fileSaveReadable.txt", "wonengbeiduquma");
        }
        /**
         * 测试写入模式的写入
         * @throws Exception
         */
        public void testSaveWriteable() throws Exception{
         FileService fileService = new FileService(this.getContext());
         fileService.saveWriteable("fileSaveWriteable.txt", "wonengbeiduquma");
        }
        /**
         * 测试读写模式的写入
         * @throws Exception
         */
        public void testSaveReadWriteable() throws Exception{
         FileService fileService = new FileService(this.getContext());
         fileService.saveReadWriteable("fileSaveReadWriteable.txt", "我能被读写吗?");
        }
        
}

七、main.xml配置:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/file_name" />

    <EditText
        android:id="@+id/fileName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/file_content" />

    <EditText
        android:id="@+id/fileContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" android:minLines="5"/>

    <Button
        android:id="@+id/fileSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/file_save" />

    <Button
        android:id="@+id/fileSaveSD"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/file_save_sd" />

</LinearLayout>

八、string.xml配置:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, FileActivity!</string>
    <string name="app_name">ExampleFileOperate</string>
    <string name="file_name">文件名称</string>
    <string name="file_content">文件内容</string>
    <string name="file_save">文件保存到手机</string>
    <string name="file_save_sd">文件保存到SD卡</string>
    <string name="success">保存完成</string>
    <string name="failure">保存失败</string>
    <string name="sdcardfail">sdCard不存在或者写保护</string>
</resources>

九、运行为:


十、可以在另一个项目中增加测试类来测试其它应用是否可以读写这些模式下创建的文件:如FileServiceTest .java:

package com.example.junit;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import android.test.AndroidTestCase;
import android.util.Log;

public class FileServiceTest extends AndroidTestCase {
    /**
     * 私用,只能本应用读写,
     * @throws Exception
     */
 public void testAccessPrivateFile() throws Exception{
  String path = "/data/data/com.example.files/files/fileSave.txt";
  File file = new File(path);
  FileInputStream fis = new FileInputStream(file);
  
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  
  int len = 0;
  while((len = fis.read(buffer))!=-1)
  {
   bos.write(buffer,0,len);
  }
  
  byte[] data = bos.toByteArray();
  bos.close();
  fis.close();
  
  String content = new String(data);
  
  Log.i("FileServiceTest",content);
 }
 /**
  * 私用  不覆盖文件,可以在文件后面追加内容
  * @throws Exception
  */
 public void testAccessAppendFile() throws Exception{
  String path = "/data/data/com.example.files/files/fileAppendSave.txt";
  File file = new File(path);
  FileInputStream fis = new FileInputStream(file);
  
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  
  int len = 0;
  while((len = fis.read(buffer))!=-1)
  {
   bos.write(buffer,0,len);
  }
  
  byte[] data = bos.toByteArray();
  bos.close();
  fis.close();
  
  String content = new String(data);
  
  Log.i("FileServiceTest",content);
 }
 /**
  * 被其他应用程序读取,不能写入
  * @throws Exception
  */
 public void testAccessReadableFile() throws Exception{
  String path = "/data/data/com.example.files/files/fileSaveReadable.txt";
  File file = new File(path);
  FileInputStream fis = new FileInputStream(file);
  
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  
  int len = 0;
  while((len = fis.read(buffer))!=-1)
  {
   bos.write(buffer,0,len);
  }
  
  byte[] data = bos.toByteArray();
  bos.close();
  fis.close();
  
  String content = new String(data);
  
  Log.i("FileServiceTest",content);
 }
 
 /**
  * 被其他应用程序写入,不能读取
  * @throws Exception
  */
 public void testAccessWriteableFileRead() throws Exception{
  String path = "/data/data/com.example.files/files/fileSaveWriteable.txt";
  File file = new File(path);
  FileInputStream fis = new FileInputStream(file);
  
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  
  int len = 0;
  while((len = fis.read(buffer))!=-1)
  {
   bos.write(buffer,0,len);
  }
  
  byte[] data = bos.toByteArray();
  bos.close();
  fis.close();
  
  String content = new String(data);
  
  Log.i("FileServiceTest",content);
 }
 /**
  * 被其他应用程序写入,不能读取
  * @throws Exception
  */
 public void testAccessWriteableFileWrite() throws Exception{
  String path = "/data/data/com.example.files/files/fileSaveWriteable.txt";
  File file = new File(path);
  FileOutputStream fos = new FileOutputStream(file,true);//第二个参数为是否要追加内容还是覆盖内容,ture为追加,false为覆盖
  fos.write("nihaoya".getBytes());
  
  fos.close();
  
 }
 
 
 /**
  * 被其他应用程序可以读写
  * @throws Exception
  */
 public void testAccessReadWriteableFileRead() throws Exception{
  String path = "/data/data/com.example.files/files/fileSaveReadWriteable.txt";
  File file = new File(path);
  FileInputStream fis = new FileInputStream(file);
  
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  
  int len = 0;
  while((len = fis.read(buffer))!=-1)
  {
   bos.write(buffer,0,len);
  }
  
  byte[] data = bos.toByteArray();
  bos.close();
  fis.close();
  
  String content = new String(data);
  
  Log.i("FileServiceTest",content);
 }
 /**
  * 被其他应用程序可以读写
  * @throws Exception
  */
 public void testAccessReadWriteableFileWrite() throws Exception{
  String path = "/data/data/com.example.files/files/fileSaveReadWriteable.txt";
  File file = new File(path);
  //此写入方法append=true时为追加模式,可以不对原文件进行覆盖
  FileOutputStream fos = new FileOutputStream(file,true);
  fos.write("恭喜你,你能加我啦!".getBytes());
  
  fos.close();
  
 }
}


十一、注意事项:

        1、要在sdcard创建和删除以及写入数据必须添加下面两个权限:

            <!-- 往SDCard的创建与删除文件权限 -->
             <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
             <!-- 往SDCard写入数据权限 -->
             <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

       2、往sdcard上写入数据是可以先判断是否有此权限:

              //判断SDCard是否存在并且可以读写

             Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED

        3、在sdcard上创建文件夹的方法(推荐后面一种方法):

            File file = new File("/mnt/sdcard/myfiles");

            if(!file.exists()){
                 file.mkdir();
            }

            或者

            File sd=Environment.getExternalStorageDirectory(); 
            String path=sd.getPath()+"/myfiles"; 
            File file=new File(path); 
            if(!file.exists()){
               file.mkdir();
            }

          4、多熟悉输入输出流的灵活应用

更多详细信息请查看java教程网 http://www.itchm.com/forum-59-1.html
分享到:
评论

相关推荐

    Android文件读写包含SDCard

    本篇将重点讲解如何在Android中进行文件读写,包括对内部存储和外部存储(即SDCard)的操作。 首先,了解Android的存储体系至关重要。Android设备有两种主要的存储类型:内部存储和外部存储。内部存储通常用于应用...

    android开发实例-sdcard文件读写及WIFI检测

    以上就是关于Android开发中SD卡文件读写和Wi-Fi检测的基本操作。在实际应用中,你可能还需要考虑异常处理、多线程、进度显示等细节。结合提供的压缩包文件,你可以进一步研究示例代码,加深理解并应用于自己的项目中...

    Android应用源码SdCard读写文件实例.zip

    在Android平台上,对SDCard(外部存储)进行文件读写是常见的操作,这对于应用程序扩展功能、存储用户数据或实现文件共享至关重要。这份"Android应用源码SdCard读写文件实例.zip"包含了示例代码,可以帮助开发者理解...

    sdcard文件读写案例-ES文件浏览器

    本案例聚焦于使用ES文件浏览器进行SD卡文件的操作,它是一款流行的Android文件管理应用,允许用户方便地浏览、编辑和管理设备上的文件。以下是关于"sdcard文件读写案例-ES文件浏览器"的相关知识点: 1. **SD卡访问...

    android项目中读取ini配置文件

    - 如果`ini`文件需要频繁修改,考虑使用SQLite数据库或者SharedPreferences存储,因为它们提供了更完善的读写操作。 7. **测试与调试** 在实际项目中,可以通过编写单元测试或者集成测试来确保ini文件读取和解析...

    android文件读取、写入(自带空间、SDCard)的记事本程序程序

    下面将详细阐述Android文件读写以及如何在自带空间和SDCard之间切换。 一、Android文件系统 1. 内部存储:内部存储是Android设备为每个应用分配的私有存储空间,只有安装了该应用的用户才能访问。内部存储的文件...

    Android数据存储之Sdcard

    总结起来,Android在Sdcard上的数据存储涉及权限管理、路径操作以及文件I/O操作。在实际应用中,开发者应根据需求选择合适的存储方式,并确保遵循最新的Android存储策略,以保证应用的兼容性和安全性。

    Android实现内存中数据保存到sdcard的方法

    总的来说,Android应用通过文件读写和I/O操作可以方便地将内存中的数据保存到SDcard,但要注意权限管理和异常处理,以确保数据的安全性和应用的稳定性。同时,了解不同编码格式的适用场景,以及如何正确关闭流,都是...

    Android 平台上SDCard的自动mount的解决方法

    本文将根据提供的文件标题、描述、标签以及部分内容,详细介绍如何在Android平台上实现SDCard的自动mount。 #### 确保SDCard驱动正常编译和使用 首先,确保SDCard的驱动程序已正确编译并且能够在Android设备上正常...

    Android保存文件到SD卡

    在Android系统中,将文件保存到SD卡是应用程序常见的需求之一,特别是在处理大量数据或多媒体文件时。Android提供了多种方式来实现这一功能,包括使用Java I/O流、Android的File类以及ContentProvider。下面我们将...

    Android将网上图片存储到sdcard中并显示出来的源码

    在Android中,访问SDCard需要在`AndroidManifest.xml`文件中添加读写权限。对于Android 6.0(API级别23)及更高版本,还需要在运行时请求这些权限。对应的权限声明如下: ```xml &lt;uses-permission android:name=...

    六、把文件存放在SDCard

    标题"六、把文件存放在SDCard"意味着我们将关注如何利用Android API将文件保存到外部存储空间。以下是一些关键知识点: 1. **获取外部存储路径**: Android提供了`Environment.getExternalStorageDirectory()`方法...

    android文件系统浏览器

    本文将围绕“Android文件系统浏览器”这一主题,深入探讨其功能、工作原理以及如何实现对SDCard的文件浏览。 首先,我们要理解Android文件系统的结构。Android采用Linux内核,因此其文件系统与传统的Linux文件系统...

    Android开发实现保存图片到手机相册功能

    当我们需要在Android应用程序中保存图片到手机相册时,需要考虑多种因素,例如手机品牌、图片格式、文件操作技巧等。本文将详细介绍Android开发实现保存图片到手机相册功能的实现方法和相关知识点。 一、图片格式的...

    应用源码SdCard读写文件实例.zip

    在Android开发中,读写外部存储(如SDCard)是常见的操作,这通常涉及到文件系统的交互和权限管理。本资源“应用源码SdCard读写文件实例.zip”提供了具体的示例代码,可以帮助开发者深入理解如何在Android应用程序中...

    android 下载图片到本地Sdcard

    这个过程涉及到网络请求、数据流处理以及文件操作等多个方面。接下来,我们将深入探讨如何实现这个功能。 首先,你需要在AndroidManifest.xml文件中添加必要的权限,以便读写外部存储: ```xml &lt;uses-permission ...

    android SD卡的读写

    本示例教程将详细解释如何在Android应用中实现SD卡的读写操作,特别是在用户界面(UI)中通过EditText组件进行数据交互。 首先,确保你的AndroidManifest.xml文件中包含了以下权限,这是读写SD卡所必需的: ```xml...

    Android写入SDCard

    在这个例子中,我们首先通过`Environment.getExternalStorageDirectory()`方法获取SDCard的根目录,然后创建一个`File`对象表示要保存的文件,并通过`FileOutputStream`对象将其写入到SDCard中。 #### 六、注意事项...

    android之网络文件下载保存到SD_card上

    在Android平台上,将网络文件下载并保存到SD ...总之,Android应用下载网络文件并保存到SD Card涉及多个步骤,包括权限设置、SD Card状态检查、文件操作以及网络请求。正确处理这些环节,才能确保文件成功下载并保存。

Global site tag (gtag.js) - Google Analytics