1 package com.lixu.writetosd;
 2 
 3 import java.io.File;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import android.app.Activity;
 7 import android.os.Bundle;
 8 import android.os.Environment;
 9 import android.widget.Toast;
10 
11 public class MainActivity extends Activity {
12 
13     @Override
14     protected void onCreate(Bundle savedInstanceState) {
15         super.onCreate(savedInstanceState);
16         setContentView(R.layout.activity_main);
17         // 判断SD卡是否装载成功,否则提示错误。
18         boolean isMounted = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
19 
20         if (isMounted) {
21             writetoSDcard();
22             Toast.makeText(this, "写入成功!", 0).show();
23         } else {
24             Toast.makeText(this, "SD卡未装载!", 0).show();
25         }
26 
27     }
28 
29     public void writetoSDcard() {
30 
31         FileOutputStream fos = null;
32         File path = Environment.getExternalStorageDirectory();
33         File dir = new File(path.getAbsoluteFile(), "lixu");
34         // 创建特定名字的文件夹 判断文件夹是否存在,不存在创建。
35         if (!dir.exists())
36             dir.mkdir();
37         // 定义特定名字的文件
38         File file = new File(dir.getAbsoluteFile(), "lixu.txt");
39         String str = "看到这句话就写入成功了!";
40         byte[] buffer = str.getBytes();
41 
42         try {
43             // 创建文件
44             file.createNewFile();
45             fos = new FileOutputStream(file);
46             // 先将字符串装入字节数组后一次写入fos流,这样相当于缓存入一个容器再写入,效率高。
47             fos.write(buffer, 0, buffer.length);
48             fos.flush();
49 
50         } catch (IOException e) {
51             e.printStackTrace();
52         } finally {
53             if (fos != null) {
54                 try {
55                     fos.close();
56                 } catch (IOException e) {
57                     e.printStackTrace();
58                 }
59             }
60         }
61 
62     }
63 
64 }

 别忘记添加权限:

posted on 2015-11-23 10:33  0代码狂人0  阅读(742)  评论(0编辑  收藏  举报