android开发之路10(文件的读写)

1.安卓中文件的数据存储实例(将文件保存到手机自带存储空间中):

①MainActivity.java

public class MainActivity extends Activity implements OnClickListener{

private Button mButton;

private EditText etFilename;

private EditText etFileContent;

/**

 * 文件的保存:

 * 第一步:创建布局文件(包括文件名的填写,内容的填写);

 * 第二步:在我们的主Activity中获取控件的对象,并给按钮设置监听器,用来完成获取填写内容,和保存文件的操作

 * 第三步:通常我们都会将项目中的业务类放到service层中,因此我们需要创建业务类,并完成文件的写入功能

 */

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mButton=(Button) findViewById(R.id.button);

        mButton.setOnClickListener(this);

        

    }

@Override

public void onClick(View v) {

etFilename=(EditText) findViewById(R.id.filename);

etFileContent=(EditText) findViewById(R.id.filecontent);

String filename=etFilename.getText().toString();

String filecontent=etFileContent.getText().toString();

FileService service=new FileService(getApplicationContext());

 

try {

service.save(filename,filecontent);

Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();

} catch (Exception e) {

Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_LONG);

e.printStackTrace();

}

}

 

②FileService .java

public class FileService {

private Context context;

 

public FileService(Context context) {

this.context = context;

}

//保存文件到手机内部存储

public void save(String filename,String filecontent) throws Exception{

/**

 * FileOutputStream:文件输出流

 * openFileOutput()方法中:

 * 参数1.要保存的文件名称;参数2.保存文件的操作模式

 * 这里我们使用私有操作模式,即创建出来的文件只能被本应用访问,其他应用无法访问该文件,

 * 另外采用私有操作模式创建的文件,写入文件中的内容会覆盖源文件的内容

 */

FileOutputStream outputStream=context.openFileOutput(filename, Context.MODE_PRIVATE);

outputStream.write(filecontent.getBytes());

outputStream.close();

}

//读取文件从手机内部存储

public String read(String filename) throws Exception{

//FileInputStream:文件输入流 

FileInputStream inputStream=context.openFileInput(filename);

ByteArrayOutputStream outputStream=new ByteArrayOutputStream();

byte[] buffer=new byte[1024];

int len=0;

while((len=inputStream.read(buffer)) != -1){

outputStream.write(buffer, 0, len);

}

byte[] data=outputStream.toByteArray();

 

return new String(data);

 

}

 

 

}

③单元测试类:FileServiceTest .java

public class FileServiceTest extends AndroidTestCase{

 

private static final String TAG="FileServiceTest";

//单元测试方法testSave()方法用来测试我们的save(String filename,String filecontent)方法是否有错

public void testSave() throws Throwable{

FileService service=new FileService(this.getContext());

service.save("456.txt", "sdfdgsdfasd");

Log.i(TAG, "成功");

}

//单元测试testRead()方法用来测试我们的read(String filename)方法是否有错

public void testRead() throws Throwable{

FileService service=new FileService(this.getContext());

String result=service.read("123.txt");

Log.i(TAG, result);

}

}

④清单文件AndroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.rookie.test1"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="10"

        android:targetSdkVersion="10" />

    <!--指定单元测试的唯一标识  -->

<instrumentation 

    android:name="android.test.InstrumentationTestRunner"

    android:targetPackage="com.rookie.test1"

    android:label="testapp"/>

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <!--添加单元测试环境  -->

        <uses-library android:name="android.test.runner"/>

        <activity

            android:name=".MainActivity"

            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>

 

</manifest>

⑤布局文件activity_main.xml(省略)

 

2.安卓中文件的数据存储实例(将数据保存到手机的SD卡中)

要想将数据保存到sd卡中,我们首先要在清单文件中设置相关的使用权限,

如:

<!--在sd卡中创建文件与删除文件的权限  -->

    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

    <!--往sd卡中写入数据的权限  -->

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

然后我们需要在上面的那个实例中的FileService.java添加一个方法,

用来保存文件到手机sdcard

public void saveToSDCard(String filename,String filecontent) throws Exception{

File file=new File(Environment.getExternalStorageDirectory(), filename);

FileOutputStream outputStream=new FileOutputStream(file);

outputStream.write(filecontent.getBytes());

outputStream.close();

}

然后我们需要在MainActivity.java文件中将之前重写的onClick()方法改写成:

@Override

public void onClick(View v) {

etFilename=(EditText) findViewById(R.id.filename);

etFileContent=(EditText) findViewById(R.id.filecontent);

String filename=etFilename.getText().toString();

String filecontent=etFileContent.getText().toString();

FileService service=new FileService(getApplicationContext());

 

try {

//判断sd卡是否存在,并可以读写

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

service.saveToSDCard(filename, filecontent);

Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();

}else{

Toast.makeText(getApplicationContext(), R.string.sd_error, Toast.LENGTH_LONG).show();

}

 

} catch (Exception e) {

Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_LONG);

e.printStackTrace();

}

至此,我们已经完成了文件写入sd卡的功能代码,那么运行一下试试看吧!

posted @ 2016-03-19 11:42  smallkure  阅读(5339)  评论(0编辑  收藏  举报