• 往SD卡中写文件的方法。


     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 }

     别忘记添加权限:

  • 相关阅读:
    nginx2
    nginx1
    将Tomcat设置为自动启动的服务最快捷方法
    keepalived VS zookeeper
    Linux CentOS 7 下 Apache Tomcat 7 安装与配置
    使用curl 命令模拟POST/GET请求
    netty3---传统IO,NIO,nettyIO
    个人或小型企业站该如何选择服务器?
    如果你不懂备案,那我简单点跟你说
    SAE Java相关问题小结
  • 原文地址:https://www.cnblogs.com/labixiaoxin/p/4987637.html
Copyright © 2020-2023  润新知