【问题标题】:How to rename an private file of my application?如何重命名我的应用程序的私有文件?
【发布时间】:2010-03-15 10:37:34
【问题描述】:

我想重命名使用 openFileOutput() 创建的上下文私有文件,但我不知道如何...

我试过了:

File file = getFileStreamPath(optionsMenuView.getPlaylistName()); // this file already exists

                try {
                    FileOutputStream outStream = openFileOutput(newPlaylistName, Context.MODE_WORLD_READABLE); // i create a new file with the new name
                    outStream.close();
                }
                catch (FileNotFoundException e) {
                    Log.e(TAG, "file not found!");
                    e.printStackTrace();
                } 
                catch (IOException e) {

                    Log.e(TAG, "IO exception");
                    e.printStackTrace();
                }                           

                Log.e(TAG, "rename status: " + file.renameTo(getFileStreamPath(newPlaylistName))); //it return true 

此代码抛出 FileNotFoundException 但文档说“打开与此上下文的应用程序包关联的私有文件以进行写入。如果文件不存在则创建文件。”所以应该在磁盘上创建新文件。 问题:当我尝试从新重命名的文件中读取时,我得到了 FileNotFoundException!

谢谢!

【问题讨论】:

    标签: android


    【解决方案1】:

    以下是重命名存储在应用私有商店中的文件的方法:

    // Renames a file stored in the application's private store.
    public static void RenameAppFile(Context context, String originalFileName, String newFileName) {
        File originalFile = context.getFileStreamPath(originalFileName);
        File newFile = new File(originalFile.getParent(), newFileName);
        if (newFile.exists()) {
            // Or you could throw here.
            context.deleteFile(newFileName);        
        }
        originalFile.renameTo(newFile);
    }
    

    【讨论】:

      【解决方案2】:

      为什么不直接使用File 类的renameTo() 方法?

      【讨论】:

      • renameTo() from File 不适用于内部存储文件
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多