2014-01-08 26 views
0

我在上傳到服務器之前重命名圖像文件時遇到問題。我正在使用以下代碼。在這裏,我正在從庫中選擇文件並重命名。如何重命名文件befor上傳到服務器

if(requestCode==SAVE_IMAGE && resultCode==Activity.RESULT_OK) 
    { 
     System.out.println("in if()"); 

     Uri selectedImage = data.getData(); 
     String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

     Cursor cursor = getContentResolver().query(selectedImage, 
       filePathColumn, null, null, null); 
     cursor.moveToFirst(); 

     int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
     path = cursor.getString(columnIndex); 

     cursor.close(); 
     String path1= "/mnt/sdcard/"; 
     File f1= new File(path); 
     File f2= new File(path1); 
     f1.renameTo(new File(f2.getAbsoluteFile()+"BBNL_OP49"+"."+"jpg")); 
     } 

當我上傳的文件與f1.getAbsoluteFile()文件名是相同的選定的文件。

回答

0

通過將文件移動到新名稱來重命名該文件。 (文件實用程序是Apache下議院IO LIB)

String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName; 
    File newFile = new File(newFilePath); 

    try { 
    FileUtils.moveFile(oldFile, newFile); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 

(OR)

// File (or directory) with old name 
    File file = new File("oldname"); 

    // File (or directory) with new name 
    File file2 = new File("newname"); 
    if(file2.exists()) throw new java.io.IOException("file exists"); 

    // Rename file (or directory) 
    boolean success = file.renameTo(file2); 
    if (!success) { 
     // File was not successfully renamed 
    } 

追加到新文件:

java.io.FileWriter out= new java.io.FileWriter(file2, true /** append=yes */); 
+0

我試過了。重命名是成功的。但是當我試圖上傳重命名的文件時,它給了文件沒有發現的異常。 –