天天看點

Android 建立檔案,删除檔案,加載本地txt檔案,string轉txt檔案,建立檔案夾,讀取檔案夾建立圖檔檔案

1、建立檔案

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

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

建立圖檔檔案

final File file = File.createTempFile(UUID.randomUUID().toString() + "", ".jpg");
           

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;
}
           

5、建立檔案夾

// 檔案存儲
private File updateDir = null;      
// 建立檔案
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
    updateDir = new File(Environment.getExternalStorageDirectory(), "data/cn.dlc.xiaoyao/msc2");
    if (!updateDir.exists()) {
        updateDir.mkdirs();
        LogPlus.i("lgq","bbh-ss-video_savePath--333-  ");
    }
}      

6、讀取檔案夾内容 

File sceneFile = new File(Environment.getExternalStorageDirectory(), "data/cn.dlc.xiaoyao/msc1");
LogPlus.i("lgq","bbh-ss-video_savePath---  "+sceneFile.exists());

File[] files = sceneFile.listFiles();

if (null != files) {

    for (int i = 0; i < files.length; i++) {

        LogPlus.e("lgq檔案夾下的檔案:" + files[i].getName()+"......"+files[i].getPath()+"..."+getAudioFileVoiceTime(files[i].getPath()));

    }

}      

繼續閱讀