2012-05-03 43 views
27

Trong ứng dụng của tôi, tôi cần phải quay video. Trước khi bắt đầu ghi âm, tôi chỉ định tên và thư mục cho nó. Sau khi ghi xong người dùng có khả năng đổi tên tập tin của mình. Tôi đã viết mã sau nhưng có vẻ như nó không hoạt động.android, Cách đổi tên tệp?

Khi người dùng nhập vào tên của tập tin và click vào nút Tôi sẽ làm điều này:

private void setFileName(String text) {  
     String currentFileName = videoURI.substring(videoURI.lastIndexOf("/"), videoURI.length()); 
     currentFileName = currentFileName.substring(1); 
     Log.i("Current file name", currentFileName); 

     File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), MEDIA_NAME); 
     File from  = new File(directory, "currentFileName"); 
     File to  = new File(directory, text.trim() + ".mp4"); 
     from.renameTo(to); 
     Log.i("Directory is", directory.toString()); 
     Log.i("Default path is", videoURI.toString()); 
     Log.i("From path is", from.toString()); 
     Log.i("To path is", to.toString()); 
    } 

Text: là tên được nhập vào bởi người sử dụng. Tên tập tin hiện tại: là tên mà được gán bởi tôi trước khi ghi MEDIA_NAME: tên của thư mục

Logcat thấy điều này:

05-03 11:56:37.295: I/Current file name(12866): Mania-Karaoke_20120503_115528.mp4 
05-03 11:56:37.295: I/Directory is(12866): /mnt/sdcard/Movies/Mania-Karaoke 
05-03 11:56:37.295: I/Default path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/Mania-Karaoke_20120503_115528.mp4 
05-03 11:56:37.295: I/From path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/currentFileName 
05-03 11:56:37.295: I/To path is(12866): /mnt/sdcard/Movies/Mania-Karaoke/hesam.mp4 

Bất kỳ đề nghị sẽ được đánh giá.

Trả lời

17

Vấn đề là trong dòng này,

File from = new File(directory, "currentFileName"); 

Đây currentFileName thực sự là một String bạn không cần phải sử dụng "

thử nó theo cách này,

File from  = new File(directory, currentFileName ); 
            ^   ^  //You dont need quotes 
+2

oh, chúa ơi! Những gì sai lầm ngu ngốc đó là tôi đã làm !!!! Cảm ơn Sanjay thân yêu. Bây giờ, nó hoạt động tốt sau khi tôi thay đổi điều đó. – Hesam

+7

@Hesam Đôi khi những sai lầm ngớ ngẩn đó mất tất cả thời gian của chúng tôi .. :) chúc mừng ... Vui lòng viết mã :) – COD3BOY

+1

lol, mọi người phạm sai lầm nhưng đây thực sự là một điều thú vị, chỉ cần nghỉ ngơi và chỉ trở lại sau khi bạn tràn đầy sinh lực . – Krypton

1

Cung cấp đối tượng Tệp đích với tên tệp khác.

// Copy the source file to target file. 
// In case the dst file does not exist, it is created 
void copy(File source, File target) throws IOException { 

    InputStream in = new FileInputStream(source); 
    OutputStream out = new FileOutputStream(target); 

    // Copy the bits from instream to outstream 
    byte[] buf = new byte[1024]; 
    int len; 

    while ((len = in.read(buf)) > 0) { 
     out.write(buf, 0, len); 
    } 

    in.close(); 
    out.close(); 
} 
+1

Nếu tệp lớn, phương pháp này có thể kích hoạt 'OutOfMemoryError' ... – nanounanue

+0

@nanounanue: tại sao? Nó đọc/ghi 1kB tại một thời điểm. – Harvey

1

bạn nên kiểm tra xem thư mục có tồn tại không!

File directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), MEDIA_NAME); 
if(!directory.exist()){ 
    directory.mkdirs(); 
} 
36

Trong mã của bạn:

nên không nó là:

File from = new File(directory, currentFileName);

thay vì

File from = new File(directory, "currentFileName");


Để đảm bảo an toàn,

Sử dụng File.renameTo(). Nhưng kiểm tra sự tồn tại của thư mục trước khi đổi tên nó!

File dir = Environment.getExternalStorageDirectory(); 
if(dir.exists()){ 
    File from = new File(dir,"from.mp4"); 
    File to = new File(dir,"to.mp4"); 
    if(from.exists()) 
     from.renameTo(to); 
} 

Tham khảo: http://developer.android.com/reference/java/io/File.html#renameTo%28java.io.File%29

+3

Tôi tiếp tục quay lại giải pháp này sau mỗi vài tháng. Cảm ơn bạn ngen cho giải pháp ngắn gọn. <3 – Sipty

2

dụ làm việc ...

File oldFile = new File("your old file name"); 
    File latestname = new File("your new file name"); 
    boolean success = oldFile .renameTo(latestname); 

    if(success) 
    System.out.println("file is renamed.."); 
+1

tốt nhất !! bỏ phiếu! – Fortran

3

/** 
* ReName any file 
* @param oldName 
* @param newName 
*/ 
public static void renameFile(String oldName,String newName){ 
    File dir = Environment.getExternalStorageDirectory(); 
    if(dir.exists()){ 
     File from = new File(dir,oldName); 
     File to = new File(dir,newName); 
     if(from.exists()) 
      from.renameTo(to); 
    } 
} 
6

Sử dụng phương pháp này để đổi tên một tập tin. Tệp from sẽ được đổi tên thành to.

private boolean rename(File from, File to) { 
    return from.getParentFile().exists() && from.exists() && from.renameTo(to); 
} 

Ví dụ mã:

public class MainActivity extends Activity { 
    private static final String TAG = "YOUR_TAG"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     File currentFile = new File("/sdcard/currentFile.txt"); 
     File newFile new File("/sdcard/newFile.txt"); 

     if(rename(currentFile, newFile)){ 
      //Success 
      Log.i(TAG, "Success"); 
     } else { 
      //Fail 
      Log.i(TAG, "Fail"); 
     } 
    } 

    private boolean rename(File from, File to) { 
     return from.getParentFile().exists() && from.exists() && from.renameTo(to); 
    } 
} 
1

Đây là những gì tôi đã kết thúc sử dụng. Nó xử lý trường hợp có một tệp hiện có với cùng tên bằng cách thêm một số nguyên vào tên tệp.

@NonNull 
private static File renameFile(@NonNull File from, 
           @NonNull String toPrefix, 
           @NonNull String toSuffix) { 
    File directory = from.getParentFile(); 
    if (!directory.exists()) { 
     if (directory.mkdir()) { 
      Log.v(LOG_TAG, "Created directory " + directory.getAbsolutePath()); 
     } 
    } 
    File newFile = new File(directory, toPrefix + toSuffix); 
    for (int i = 1; newFile.exists() && i < Integer.MAX_VALUE; i++) { 
     newFile = new File(directory, toPrefix + '(' + i + ')' + toSuffix); 
    } 
    if (!from.renameTo(newFile)) { 
     Log.w(LOG_TAG, "Couldn't rename file to " + newFile.getAbsolutePath()); 
     return from; 
    } 
    return newFile; 
}