欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android中把文件保存到sdcard代码实例

程序员文章站 2024-01-15 09:20:34
直接上代码: package com.example.test; import java.io.file; import java.io.filenotf...

直接上代码:

package com.example.test;

import java.io.file;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;

import android.os.bundle;
import android.os.environment;
import android.app.activity;
import android.widget.toast;

public class mainactivity extends activity {
  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);
    
    //要保存的文件名和文件内容
    string filename = "test.txt";
    string content = "this is a test.";
    
    //判断sdcard是否存在
    string state = environment.getexternalstoragestate();
    if(state.equals(environment.media_mounted)) {
     //获取sdcard目录
     file sdcardpath = environment.getexternalstoragedirectory();
     
     file file = new file(sdcardpath, filename);
     fileoutputstream fos;
  try {
  fos = new fileoutputstream(file);
  fos.write(content.getbytes());
  fos.close();
  } catch (filenotfoundexception e) {
  e.printstacktrace();
  } catch (ioexception e) {
  e.printstacktrace();
  }
  toast.maketext(this, "保存成功", toast.length_short).show();
    } else {
     toast.maketext(this, "sdcard不存在获取不可写入", toast.length_short).show();
    }
    
  }
}