代码之家  ›  专栏  ›  技术社区  ›  Ungureanu Liviu

如何重命名我的应用程序的私有文件?

  •  1
  • Ungureanu Liviu  · 技术社区  · 16 年前

    我想重命名一个用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!

    非常感谢。

    2 回复  |  直到 16 年前
        1
  •  1
  •   Mark B    16 年前

    为什么不直接使用 File renameTo()

        2
  •  2
  •   Mr. Bungle    14 年前

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

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