Android第四个功能:文件读取,并且用单元测试进行测试
16lz
2021-01-26
添加的核心代码三部分:
1、FileService.java中添加五个读取的方法
2、新建一个测试类FileServiceTest.java
3、AndroidManifest.xml中添加导入,和指定测试运行器,及包
在上一个功能的项目中继续完成
/** * 读取文件内容 * @param filename 文件名称 * @return 文件内容 * @throws Exception */public String read(String filename) throws Exception {FileInputStream inStream = context.openFileInput(filename);ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {outStream.write(buffer, 0, len);}byte[] data = outStream.toByteArray();return new String(data);}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.dcj" 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=".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> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.dcj" android:label="Test for my App"/></manifest>
package com.dcj.test;import com.dcj.service.FileService;import android.test.AndroidTestCase;import android.util.Log;public class FileServiceTest extends AndroidTestCase {private static final String TAG = "FileServiceTest";public void testRead() throws Exception {FileService service = new FileService(this.getContext());String result = service.read("dcj.txt");Log.i(TAG, result);}}
写好之后运行FileServiceTest文件,然后查看LogCat
更多相关文章
- git使用小结
- Weex系列(序) —— 总要知道原生的一点东东(Android)
- Android中存储目录
- Android(安卓)studio 为项目添加启动等待界面
- TabLayout+ViewPager+Fragment实现底部导航
- 向sdcard添加文件fail可能的情况
- [2010-12-31 21:33:29 - s] W/ResourceType(27930): Unable to g
- Android(安卓)数据存储之 文件存储
- make_ext4fs 文件权限控制