安卓系统,如何重命名文件?

50

在我的应用程序中,我需要记录视频。在开始录制之前,我会为其指定一个名称和目录。录制完成后,用户可以重命名文件。我编写了以下代码,但似乎不起作用。

当用户输入文件名并单击按钮时,我会执行以下操作:

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

欢迎提出任何建议。

10个回答

66

在你的代码中:

应该是:

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


7
我每隔几个月都会回到这个解决方案。感谢ngen提供简明的解决方案。<3 - Sipty
@Igor 这个问题是针对特定操作系统的,即 Android 操作系统。 - David Conrad

24

问题出在这一行代码上:

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

这里的currentFileName实际上是一个字符串,你不必使用"

可以尝试这种方式:

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

3
哦,我的天!我犯了多么愚蠢的错误!!!谢谢亲爱的桑杰。我更改后它现在运行良好。 - Hesam
9
有时候这种愚蠢的错误会占用我们所有的时间.. :) 干杯..愉快编码 :) - COD3BOY
2
哈哈,每个人都会犯错,但这真的很有趣。休息一下,等你充满能量后再回来处理它。 - Krypton

13

使用此方法以重命名文件。文件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);
    }
}

1
新文件声明中缺少"="。 - mathias.horn

6

/**
 * 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

操作示例...

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

2
提供不同文件名的目标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();
}

1

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

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

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

}

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

0
在Kotlin中,这种方式非常有用,您不需要任何权限,因为此文件夹是您应用程序包名称的子文件夹。
try {
                val dir =context.getDir("Music", AppCompatActivity.MODE_PRIVATE)
                if (dir.exists()) {
                    val from = File(dir, "old_name.mp3")
                    val to = File(dir, "new_Name.mp3")
                    if (from.exists()) from.renameTo(to)
                }
    } catch (e: IOException) {
                e.printStackTrace()
               
            }catch (e:NullPointerException){
                e.printStackTrace()
              
            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接