【问题标题】:saving, reading and securing data of apps directory in android在 android 中保存、读取和保护应用程序目录的数据
【发布时间】:2016-06-01 12:43:19
【问题描述】:

我正在尝试将文件保存到内部存储器中,并且应该只能由我的应用程序读取。 到目前为止,我已经尝试过了。

  String filesave  =     Environment.getExternalStorageDirectory()+""+getFilesDir()+"/.fkfk";
    File f = new File(filesave);
    if (!f.exists()){
        f.mkdir();
    }
File sd = Environment.getExternalStorageDirectory();
    Log.e("files", Environment.getExternalStorageDirectory()+f.getAbsolutePath());
String path  = Environment.getExternalStorageDirectory()+"/.NEWFolders/hdfc0002.jpg";
    File toCopy = new File(path);
    if (toCopy.exists()){
        Log.e("ok","got the path");
        try{
            if (sd.canWrite()) {
                File source= toCopy;
                File destination=f;
                if (source.exists()) {
                    FileChannel src = new FileInputStream(source).getChannel();
                    FileChannel dst = new FileOutputStream(destination).getChannel();
                    if (dst != null && source != null) {
                        dst.transferFrom(src, 0, src.size());
                    }
                    if (src != null) {
                        src.close();
                    }
                    if (dst != null) {
                        dst.close();
                    }
                }else {
                    FileChannel src = new FileInputStream(source).getChannel();
                    FileChannel dst = new FileOutputStream(destination).getChannel();
                    if (dst != null && source != null) {
                        dst.transferFrom(src, 0, src.size());
                    }
                    if (src != null) {
                        src.close();
                    }
                    if (dst != null) {
                        dst.close();
                    }
                }
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

    }

但是这段代码 sn-p 抛出 FileNotFound 异常。 请同样建议我。 提前致谢

【问题讨论】:

    标签: android file security android-internal-storage


    【解决方案1】:

    这是搞混了:

    Environment.getExternalStorageDirectory()+""+getFilesDir()+"/.fkfk";
    

    Environment.getExternalStorageDirectory 和 Context 的 getFiledDir() 方法指的是两个完全不同的位置 - 第一个在主“外部存储”(现在通常是设备的永久部分)上,第二个在应用程序的私人存储区。

    您应该只使用其中一种方法来发现最适合您目标的位置。您可以参考 Android 文档中的 Storage OptionsSaving Files 来帮助您做出决定。如果您希望某些内容仅供您的应用使用,您通常需要内部存储 - 即 getFilesDir()。

    一旦你选择了一个位置,你需要让你的其余代码与它保持一致。

    【讨论】:

    • 我想使用私有数据目录来申请,请您详细说明一下
    • 查看所提供的 android 文档的链接。
    猜你喜欢
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 2022-06-19
    相关资源
    最近更新 更多