Business Layer Code:
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; Public fileservice (context) {super (); this. context = context;} // Save Public void save (string filename, string content) throws exception {fileoutputstream Fos = Co Ntext. openfileoutput (filename, context. mode_private); FOS. write (content. getbytes (); FOS. close () ;}// read data Public String readfile (string filename) throws ioexception {fileinputstream FCM = context. openfileinput (filename); int Len = 0; byte [] buffer = new byte [1024]; bytearrayoutputstream baos = new bytearrayoutputstream (); // output data to the memory while (LEN = Fi. read (buffer ))! =-1) {// if the data volume is large, the 2nd read data may overwrite the 1st read data to baos. write (buffer, 0, Len);} byte [] DATA = baos. tobytearray (); // obtain the baos in which data is stored in binary format. close (); FCM. close (); return new string (data); // convert binary data to the corresponding string }}
Unit test environment setup:
Add the code under <Application> </Application> In androidmanifest. xml:
<uses-library android:name="android.test.runner" />
Add the code outside <Application> </Application>:
<instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="cn.bzu.fileoperation" > </instrumentation>
Business Layer Test code:
Package CN. BZU. fileoperation; import Java. io. ioexception; import android. test. androidtestcase; public class fileservicetest extends androidtestcase {public void testsavefile () {fileservice = new fileservice (getcontext (); try {fileservice. save ("file2.txt", "");} catch (exception e) {// todo auto-generated catch blocke. printstacktrace () ;}} public void testreadfile () {fileservice = new fileservice (getcontext (); try {string S = fileservice. readfile ("file2.txt"); system. out. print (s);} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}
Right-click the test class -- run as -- Android JUnit test;
If no error occurs, you can run it in the virtual machine.