Android 创建文件,删除文件,加载本地txt文件,string转txt文件

1、创建文件

String fileName = "my.txt";
File fs = new File(Environment.getExternalStorageDirectory() + "/msc/" + fileName);

msc可要可不要   或者是"/"

2、删除文件

                String ss = "/mnt/sdcard/my.txt";
//                String ss = "/storage/emulated/0/Pictures/Screenshots/Screenshot_20190814-141238.jpg";
                File file = new File(ss);
                if (file.exists()){
                file.delete();
                }

 /mnt/sdcard/     等于   /storage/emulated/0/

3、string转为本地txt文件

String fileName = "my.txt";
File fs = new File(Environment.getExternalStorageDirectory()+"/"  + fileName);
if (fs.exists()){
    fs.delete();
}
String charset = "UTF-8";
// 写字符换转成字节流
try {
    FileOutputStream outputStream = new FileOutputStream(fs);
    OutputStreamWriter writer = new OutputStreamWriter(
            outputStream, charset);
    try {
        writer.write("这是要保存的中文字符aaabbbb大范围sdfsdfsf");
    } finally {
        writer.close();
    }

} catch (IOException e) {
    e.printStackTrace();
}

4、读取本地txt文件,转为string

String fname = "/mnt/sdcard/my.txt";
private String loadTXTFromSDFile(String fname) {
    String result=null;
    try {
        File f=new File(fname);
        int length=(int)f.length();
        byte[] buff=new byte[length];
        FileInputStream fin=new FileInputStream(f);
        fin.read(buff);
        fin.close();
        result=new String(buff,"UTF-8");
    }catch (Exception e){
        e.printStackTrace();
    }
    return result;
}
发布了339 篇原创文章 · 获赞 66 · 访问量 36万+

猜你喜欢

转载自blog.csdn.net/meixi_android/article/details/99584941