android,如何重命名文件?

时间:2012-05-03 04:11:02

标签: android file-rename

在我的应用程序中,我需要录制视频。在开始录制之前,我正在为其分配名称和目录。录制完成后,用户可以重命名他的文件。我写了下面的代码,但似乎不起作用。

当用户输入文件名并点击按钮时,我会这样做:

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

文字:是用户输入的名称。 当前文件名:是我在录制前分配的名称 MEDIA_NAME:文件夹名称

Logcat显示:

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

任何建议都将不胜感激。

9 个答案:

答案 0 :(得分:41)

在您的代码中

不应该是:

File from = new File(directory, currentFileName);

而不是

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


为安全起见,

使用File.renameTo()。但在重命名之前检查目录是否存在!

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

参见: http://developer.android.com/reference/java/io/File.html#renameTo%28java.io.File%29

答案 1 :(得分:18)

问题出在这一行,

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

此处currentFileName实际上是您不必使用的"

字符串

以这种方式试试,

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

答案 2 :(得分:7)

使用此方法重命名文件。文件from将重命名为to

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

示例代码:

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

答案 3 :(得分:5)

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

答案 4 :(得分:2)

工作示例......

   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..");

答案 5 :(得分:1)

使用不同的文件名提供目标File对象。

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

答案 6 :(得分:1)

你应该检查目录是否存在!

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

答案 7 :(得分:1)

这是我最终使用的。它通过向文件名添加整数来处理存在具有相同名称的现有文件的情况。

@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;
}

答案 8 :(得分:0)

    public void renameFile(File file,String suffix) {

    String ext = FilenameUtils.getExtension(file.getAbsolutePath());
    File dir = file.getParentFile();

    if(dir.exists()){
        File from = new File(dir,file.getName());
        String name = file.getName();
        int pos = name.lastIndexOf(".");
        if (pos > 0) {
            name = name.substring(0, pos);
        }
        File to = new File(dir,name+suffix+"."+ext);
        if(from.exists())
           from.renameTo(to);
    }

}