android 单元测试和文件操作
android 单元测试 配置文件所要添加的权限
application 标签中
<uses-library android:name="android.test.runner"/>
application 标签外
<uses-permission android:name="android.permission.RUN_INSTRUMENTATION"/>
<instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="larryli.com.file.activity" android:label="Test for my app"/>
判断手机存储卡是否锁定 Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
取到sdcard的路径 Environment.getExternalStorageDirectory()
************************************************************************************************
android 文件读取写入操作
public class FileService
{
private Context context;
public FileService(Context context)
{
super();
this.context = context;
}
/**
* 以私有形式保存内容到文件中(把文件保存到sdcard的根目录下)
* @param filename 文件名
* @param content 文件内容
* @throws Exception
*/
public void saveToSdcard(String filename, String content) throws Exception
{
File file=new File("/mnt/sdcard", filename);
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
/**
* 以私有形式保存内容到文件中
* @param filename 文件名
* @param content 文件内容
* @throws Exception
*/
public void save(String filename, String content) throws Exception
{
FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
/**
* 以追加形式保存内容到文件中
* @param filename 文件名
* @param content 文件内容
* @throws Exception
*/
public void saveappen(String filename, String content) throws Exception
{
FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_APPEND);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
/**
* 保存类容(允许其他应用程序读取该文件的内容)
* @param filename 文件名
* @param content 文件内容
* @throws Exception
*/
public void savereadable(String filename, String content) throws Exception
{
FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
/**
* 保存类容(允许其他应用程序往该文件写入内容)
* @param filename 文件名
* @param content 文件内容
* @throws Exception
*/
public void savewiriteable(String filename, String content) throws Exception
{
FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
}
/**
* 读取文件中的内容
* @param filename
* @return
* @throws Exception
*/
public String readFile(String filename) throws Exception
{
byte[] buffer = new byte[1024];
FileInputStream fileInputStream = context.openFileInput(filename);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
int len = 0;
while ((len = fileInputStream.read(buffer)) != -1)
{
outstream.write(buffer, 0, len);
}
byte[] data = outstream.toByteArray();
fileInputStream.close();
outstream.close();
return new String(data);
}
}