業務層類代碼:
package cn.bzu.fileoperation;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import android.content.Context;public class FileService {private Context context;public FileService(Context context) {super();this.context = context;}//儲存資料public void save(String fileName,String content) throws Exception{FileOutputStream fos=context.openFileOutput(fileName, Context.MODE_PRIVATE);fos.write(content.getBytes());fos.close();}//讀取資料public String readFile(String filename) throws IOException{FileInputStream fis=context.openFileInput(filename);int len=0;byte[] buffer=new byte[1024];ByteArrayOutputStream baos=new ByteArrayOutputStream();//往記憶體中輸出資料while((len=fis.read(buffer))!=-1){//如果資料量很大,第2次讀取的資料有可能會把第1次讀取的資料給覆蓋掉baos.write(buffer, 0, len);}byte[] data=baos.toByteArray();//得到記憶體中的資料 以二進位存放的baos.close();fis.close();return new String(data);//根據位元據轉換成所對應的字串}}
單元測試環境搭建:
在AndroidManifest.xml中<application></application>下添加代碼:
<uses-library android:name="android.test.runner" />
在<application></application>外添加代碼:
<instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="cn.bzu.fileoperation" > </instrumentation>
業務層測試類別代碼:
package cn.bzu.fileoperation;import java.io.IOException;import android.test.AndroidTestCase;public class FileServiceTest extends AndroidTestCase {public void testSaveFile(){FileService fileService=new FileService(getContext());try {fileService.save("file2.txt", "啦啦啦啦啦拉了拉啦啦啦");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void testReadFile(){FileService fileService=new FileService(getContext());try {String s=fileService.readFile("file2.txt");System.out.print(s);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
右擊測試類別——run as——android junit test;
如果運行無錯,則可以在虛擬器中運行