Android手机文件系统操作——轻松存储与获取手机文件

Android获取各种系统路径的方法

通过Environment获取的

  • Environment.getDataDirectory().getPath() :                                      获得根目录/data 内部存储路径
  • Environment.getDownloadCacheDirectory().getPath()  :               获得缓存目录/cache
  • Environment.getExternalStorageDirectory().getPath():                  获得SD卡目录/mnt/sdcard(获取的是手机外置sd卡的路径)
  • Environment.getRootDirectory().getPath() :                                     获得系统目录/system

通过Context获取的

  • Context.getDatabasePath()                                返回通过Context.openOrCreateDatabase 创建的数据库文件
  • Context.getCacheDir().getPath() :          用于获取APP的cache目录/data/data//cache目录

  • Context.getExternalCacheDir().getPath()  :                           用于获取APP的在SD卡中的cache目录/mnt/sdcard/android/data//cache

  • Context.getFilesDir().getPath()  :          用于获取APP的files目录 /data/data//files

  • Context.getObbDir().getPath():              用于获取APPSDK中的obb目录/mnt/sdcard/Android/obb/

  • Context.getPackageName() :                                                  用于获取APP的所在包目录

  • Context.getPackageCodePath()  :                                          来获得当前应用程序对应的 apk 文件的路径
  • Context.getPackageResourcePath() :                                   获取该程序的安装包路径

完整 操作手机文件 工具类:


    public void saveToPhone(View v) {
// FileDir();
        SDCardTest();
    }

    private void FileDir() {
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            // Something else is wrong. It may be one of many other states, but all we need
            // to know is we can neither read nor write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }


        Log.i("codecraeer", "getFilesDir = " + getFilesDir());
        Log.i("codecraeer", "getExternalFilesDir = " + getExternalFilesDir("exter_test").getAbsolutePath());
        Log.i("codecraeer", "getDownloadCacheDirectory = " + Environment.getDownloadCacheDirectory().getAbsolutePath());
        Log.i("codecraeer", "getDataDirectory = " + Environment.getDataDirectory().getAbsolutePath());
        Log.i("codecraeer", "getExternalStorageDirectory = " + Environment.getExternalStorageDirectory().getAbsolutePath());
        Log.i("codecraeer", "getExternalStoragePublicDirectory = " + Environment.getExternalStoragePublicDirectory("pub_test"));
    }

    /** * SDcard操作 */
    public void SDCardTest(){
        try {
            //获取扩展SD卡设备状态
            String sDStateString = Environment.getExternalStorageState();
            //拥有可读可写权限
            if(sDStateString.equals(Environment.MEDIA_MOUNTED)){
                //获取扩展存储设备的文件目录
                    File SDFile = Environment.getExternalStorageDirectory();
                String fileDirectoryPath=SDFile.getAbsolutePath()+File.separator+"测试文件夹";
                File fileDirectory=new File(fileDirectoryPath);
                //打开文件
                File myFile = new File(fileDirectoryPath+File.separator+"MyFile.txt");
                //判断是否存在,不存在则创建
                if (!fileDirectory.exists()) {
                        //按照指定的路径创建文件夹
                        fileDirectory.mkdirs();
                }
                if (!myFile.exists()) {
                    try {
                        //在指定的文件夹中创建文件
                        myFile.createNewFile();
                    } catch (Exception e) {
                    }
                }
                //写数据
                String szOutText="Hello, World!+姚佳伟";
                FileOutputStream outputStream=new FileOutputStream(myFile);
                outputStream.write(szOutText.getBytes());
                outputStream.close();
            }
            //拥有只读权限
            else if(sDStateString.endsWith(Environment.MEDIA_MOUNTED_READ_ONLY)){
                //获取扩展存储设备的文件目录
                File SDFile=android.os.Environment.getExternalStorageDirectory();
                //创建一个文件
                File myFile=new File(SDFile.getAbsolutePath()+File.separator+"MyFile.txt");
                //判断文件是否存在
                if(myFile.exists()){
                    //读数据
                    FileInputStream inputStream=new FileInputStream(myFile);
                    byte[]buffer=new byte[1024];
                    inputStream.read(buffer);
                    inputStream.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("yjw","检查权限");
        }
    }

public class FileUtils { 
    static String directoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "FileDemo" + File.separator;
    String fileName = directoryPath + getISO8601TimeFileName() + ".txt";

    //创建文件夹及文件
    public void CreateText() throws IOException {
        File file = new File(directoryPath);
        if (!file.exists()) {
            try {
                //按照指定的路径创建文件夹
                file.mkdirs();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        File dir = new File(fileName);
        if (!dir.exists()) {
            try {
                //在指定的文件夹中创建文件
                dir.createNewFile();
            } catch (Exception e) {
            }
        }
    }

    //向已创建的文件中写入数据
    public void print(String str) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        String datetime = "";
        try {
            CreateText();
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd" + " " + "hh:mm:ss");
            datetime = tempDate.format(new java.util.Date()).toString();
            fw = new FileWriter(fileName, true);//
            // 创建FileWriter对象,用来写入字符流
            /** * 如果想要每次写入,清除之前的内容,使用FileOutputStream流 */
            bw = new BufferedWriter(fw); // 将缓冲对文件的输出
            String myreadline = datetime + "[]" + str;

            bw.write(myreadline + "\n"); // 写入文件
            bw.newLine();
            bw.flush(); // 刷新该流的缓冲
            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
            try {
                bw.close();
                fw.close();
            } catch (IOException e1) {
            }
        }
    }

    /** * 此方法为android程序写入sd文件文件,用到了android-annotation的支持库@ * * @param buffer 写入文件的内容 * @param folder 保存文件的文件夹名称,如log;可为null,默认保存在sd卡根目录 * @param fileName 文件名称,默认app_log.txt * @param append 是否追加写入,true为追加写入,false为重写文件 * @param autoLine 针对追加模式,true为增加时换行,false为增加时不换行 */
    public synchronized static void writeFiledToSDCard(@NonNull final byte[] buffer, @Nullable final String folder, @Nullable final String fileName, final boolean append, final boolean autoLine) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
                String folderPath = "";
                if (sdCardExist) {
                    //TextUtils为android自带的帮助类
                    if (TextUtils.isEmpty(folder)) {
                        //如果folder为空,则直接保存在sd卡的根目录
// folderPath = Environment.getExternalStorageDirectory() + File.separator;
                        folderPath = directoryPath;
                    } else {
                        folderPath = Environment.getExternalStorageDirectory() + File.separator + folder + File.separator;
                    }
                } else {
                    return;
                }

                File fileDir = new File(folderPath);
                if (!fileDir.exists()) {
                    if (!fileDir.mkdirs()) {
                        return;
                    }
                }
                File file;
                //判断文件名是否为空
                if (TextUtils.isEmpty(fileName)) {
                    file = new File(folderPath + getISO8601TimeFileName() + ".txt");
                } else {
                    file = new File(folderPath + fileName);
                }
                RandomAccessFile raf = null;
                FileOutputStream out = null;
                try {
                    if (append) {
                        //如果为追加则在原来的基础上继续写文件
                        raf = new RandomAccessFile(file, "rw");
                        raf.seek(file.length());
                        raf.write(buffer);
                        if (autoLine) {
                            raf.write("\n".getBytes());
                        }
                    } else {
                        //重写文件,覆盖掉原来的数据
                        out = new FileOutputStream(file);
                        out.write(buffer);
                        out.flush();
                    }
                    Log.d("yjw", "writeFiledToSDCard===" + "文件存入成功");
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (raf != null) {
                            raf.close();
                        }
                        if (out != null) {
                            out.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public static String getISO8601TimeFileName() {
        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        df.setTimeZone(tz);
        String nowAsISO = df.format(new Date());
        return nowAsISO;
    }
}

参考资料:

    原文作者:姚佳伟
    原文地址: https://blog.csdn.net/fang323619/article/details/74942377
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞