android中把文件保存到sdcard代码实例
程序员文章站
2022-04-30 22:54:14
直接上代码:
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(); } } }
上一篇: 不同显示屏间的校色问题分享
下一篇: 滚动优化