业务层类代码:
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 block
e.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 block
e.printStackTrace();
}
}
}
右击测试类——run as——android junit test;
如果运行无错,则可以在虚拟器中运行