2010-03-15 47 views
1

我要重命名)与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异常,但文件说,“开放与此Context的应用程序包相关联的专用文件用于编写。创建该文件(如果该文件尚不存在)。“所以新文件应该在磁盘上创建。 问题:当我尝试从新的重命名文件读取时,我得到了FileNotFoundException!

谢谢!

回答

1

为什么不只是使用File类的renameTo()方法?

2

这里是重新命名保存在您的应用程序的专用存储文件的方法:

// 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); 
} 
相关问题