在Sd卡中新建chen文件夹前后:
前
后
新建FileService.java的代码:
package cn.example.cx9_6_datasavesdcard;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.Environment;
public class FileService
{
public boolean saveFileToSdcard(String filename, byte[] data) throws IOException
{
String state = Environment.getExternalStorageState(); // 判断sdcard的状态
FileOutputStream outputStream = null; // 表示sdcard卡挂在手机上 并且可以读写
File root = Environment.getExternalStorageDirectory(); // 获得sdcard的根目录
if (state.equals(Environment.MEDIA_MOUNTED))
{
File file = new File(root, filename);
try
{
outputStream = new FileOutputStream(file);
outputStream.write(data, 0, data.length);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} finally
{
if (outputStream != null)
{
try
{
outputStream.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
return false;
}
}
Mainactivity.java的代码不需改变;
;
新建测试类Mytext.java的代码:
package cn.example.cx9_6_datasavesdcard;
import java.io.IOException;
import android.test.AndroidTestCase;
public class Mytext extends AndroidTestCase
{
public void save() throws IOException
{
FileService service = new FileService();
service.saveFileToSdcard("chen.text", "nihaoaniazainalia".getBytes());
}
}
选中save()右击选择测试。