Подтвердить что ты не робот

Android, Как переименовать файл?

В моем приложении мне нужно записать видео. Перед началом записи я присваиваю ему имя и каталог. После завершения записи пользователь имеет возможность переименовать свой файл. Я написал следующий код, но, похоже, он не работает.

Когда пользователь вводит имя файла и нажимает кнопку, я сделаю следующее:

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

Текст: это имя, которое вводится пользователем. Current Filename: имя, которое назначено мной перед записью 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

Любое предложение будет оценено.

4b9b3361

Ответ 1

Проблема в этой строке,

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

Здесь currentFileName на самом деле является строкой, которую вы не должны использовать "

попробуйте это,

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

Ответ 2

В вашем коде:

Не должно быть:

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

Ответ 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);
    }
}

Ответ 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

Предоставить целевой объект 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();
}

Ответ 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);
    }

}