package com.lixu.writetosd; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 判断SD卡是否装载成功,否则提示错误。
boolean isMounted = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); if (isMounted) {
writetoSDcard();
Toast.makeText(this, "写入成功!", 0).show();
} else {
Toast.makeText(this, "SD卡未装载!", 0).show();
} } public void writetoSDcard() { FileOutputStream fos = null;
File path = Environment.getExternalStorageDirectory();
File dir = new File(path.getAbsoluteFile(), "lixu");
// 创建特定名字的文件夹 判断文件夹是否存在,不存在创建。
if (!dir.exists())
dir.mkdir();
// 定义特定名字的文件
File file = new File(dir.getAbsoluteFile(), "lixu.txt");
String str = "看到这句话就写入成功了!";
byte[] buffer = str.getBytes(); try {
// 创建文件
file.createNewFile();
fos = new FileOutputStream(file);
// 先将字符串装入字节数组后一次写入fos流,这样相当于缓存入一个容器再写入,效率高。
fos.write(buffer, 0, buffer.length);
fos.flush(); } catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} } }
别忘记添加权限: