【问题标题】:android, How to rename a file?android,如何重命名文件?
【发布时间】:2020-06-25 16:14:41
【问题描述】:

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

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

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

任何建议都将不胜感激。

【问题讨论】:

    标签: android file-rename


    【解决方案1】:

    在您的代码中:

    不应该吗:

    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

    【讨论】:

    • 我每隔几个月就会回到这个解决方案。感谢 ngen 提供简洁的解决方案。
    • @Igor 这个问题是特定于操作系统的,适用于 Android 操作系统。
    【解决方案2】:

    问题出在这一行,

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

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

    试试这个方法,

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

    【讨论】:

    • 天啊!我犯了什么愚蠢的错误!!!!谢谢亲爱的桑杰。现在,我改变它后它工作正常。
    • @Hesam 有时这种愚蠢的错误会占用我们所有的时间.. :) 干杯.. 编码快乐 :)
    • 大声笑,每个人都会犯错,但这真的很有趣,休息一下,等你充满活力后再回来。
    【解决方案3】:

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

    【讨论】:

    • newFile 声明中缺少“=”。
    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

      工作示例...

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

      【讨论】:

        【解决方案6】:

        为目标文件对象提供不同的文件名。

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

        【讨论】:

          【解决方案7】:

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

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

          【讨论】:

            【解决方案8】:

            这就是我最终使用的。它通过在文件名中添加一个整数来处理存在同名文件的情况。

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

            【讨论】:

              【解决方案9】:
              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);
                  }
              
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2013-06-23
                • 2016-06-13
                • 1970-01-01
                • 1970-01-01
                • 2014-05-19
                • 2012-11-09
                • 2016-04-27
                • 2016-05-20
                相关资源
                最近更新 更多