2010-03-15 46 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); 
} 
相關問題