renameTo()无法重命名图像并返回false

时间:2018-02-21 04:16:49

标签: java android file file-rename

我有一个图片库应用,我正在尝试使用renameTo()方法重命名图像,但它无法更改文件名并返回false。我在SO上阅读了很多关于重命名文件的问题,所有这些问题都只建议了一种重命名文件的方法 - renameTo()。奇怪的是,很多问题都谈到了在各种条件下重命名文件的好方法 在android中有没有其他方法重命名文件?如果我只使用这种方式,如何使它工作?

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

        alert = new AlertDialog.Builder(this);
        etRenameFile = new EditText(getApplicationContext());
        alert.setTitle("Do you want to rename the file?");
        alert.setMessage(" ");
        alert.setView(etRenameFile);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(final DialogInterface dialog, int whichButton) {
                renameFileAlert();
                adapter.notifyDataSetChanged();
            }
        });

        alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                // what ever you want to do with No option.
            }
        });

        private void renameFileAlert(){
            String renameFile = etRenameFile.getText().toString();
            Log.v(TAG, renameFile + " another");
            String filename= al_images.get(int_position).getAl_imagepath().get(fileIndex);

            File oldFilePath = new File(al_images.get(int_position).getAl_imagepath().get(fileIndex));
            Log.v(TAG,oldFilePath.toString());
            // Log.d("OLDFILEPATH", oldFilePath.toString());  // prints the correct path of the file being selected

            x = al_images.get(int_position).getAl_imagepath().get(fileIndex);
            File renamedFile = new File(x.replace(filename, renameFile));
            Log.v(TAG, renamedFile.toString() + " new name");  //prints new name of the file being entered
            // Log.d("NEWFILE", renamedFile.toString());

            boolean renamed = oldFilePath.renameTo(renamedFile);
            if(renamed){
                Log.v(TAG, "rename done");
            } else Log.v(TAG, "failed");

            notifyMediaStoreScanner(renamedFile);
        }

        public final void notifyMediaStoreScanner(File file) {
//        try {
//            MediaStore.Images.Media.insertImage(getBaseContext().getContentResolver(),
//                    file.getAbsolutePath(), file.getName(), null);
        getBaseContext().sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        getBaseContext().sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
    }

1 个答案:

答案 0 :(得分:0)

你想把它重命名为什么?当且仅当重命名成功时,renameTo()才会返回true;否则返回false。