在SD卡创建文件夹、写入文件、读取文件

来源:互联网 发布:dm500s接收机 淘宝 编辑:程序博客网 时间:2024/05/19 11:45

    <!-- SD卡内创建文件夹 -->

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

//创建文件夹

if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
// 创建一个文件夹对象,赋值为外部存储器的目录
File sdcardDir =Environment.getExternalStorageDirectory();
//得到一个路径,内容是sdcard的文件夹路径和名字
String path=sdcardDir.getPath()+"/makeByHwh";
File path1 = new File(path);
if (!path1.exists()) {
path1.mkdirs();
Toast.makeText(getApplicationContext(), "成功创建文件夹", 0).show();
}else{
Toast.makeText(getApplicationContext(), "已经存在", 0).show();
}

}

//写入数据

Writer writer = null;
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
// 创建一个文件夹对象,赋值为外部存储器的目录
File sdCard = Environment.getExternalStorageDirectory();
// 查看LogCat,获取的sd卡的绝对路径为 /storage/sdcard
sdCard = new File(sdCard, "/makeByHwh");
if (!sdCard.exists()) {
sdCard.mkdirs();
}
sdCard = new File(sdCard, "s");
FileOutputStream out;
try {
out = new FileOutputStream(sdCard);
writer = new OutputStreamWriter(out);
String str = "来自保存在内部存储设备的数据";
writer.write(str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

//读取数据

BufferedReader reader = null;
StringBuilder data = new StringBuilder();
try {
File sdCard = Environment.getExternalStorageDirectory();
sdCard = new File(sdCard, "/makeByHwh/" + "s");
FileInputStream in = new FileInputStream(sdCard);
reader = new BufferedReader(new InputStreamReader(in));
String line = new String();
while ((line = reader.readLine()) != null) {
data.append(line);
}
Toast.makeText(getApplicationContext(), data, 0).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "没有发现数据", 0).show();
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

0 0
原创粉丝点击