문제

I need to rename a file name for a android application. I wrote the code inside onListItemClick() but it is not working. I didnt get any exception either. Here is the code. What is the error here ?

File oldFile = new File(path.get(position));
        String oldFileName=path.get(position);
        Toast.makeText(this, path.get(position), Toast.LENGTH_LONG).show();
        String segments[]=oldFileName.split("/");
        String fileName=segments[segments.length-1];
        String newFileName=oldFileName.replace(fileName, "log_B.txt");
        File newFile=new File(newFileName);


    if(!oldFile.isDirectory()){

        System.out.println("File Name is:"+fileName);

        try{
            if(oldFile.renameTo(newFile)){
                System.out.println("File renamed successfull !");

            }else{
                System.out.println("File renamed operation failed");
            }


        }catch(Exception ex){
            System.out.println("Exception :"+ex.getMessage());
        }

    }else{

        System.out.println("Folder Name is :"+fileName);

    }
도움이 되었습니까?

해결책

Make sure you have write permissions defined in the manifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

The File.renameTo() method will fail under the following conditions:

  • Write permission is required on the directories containing both the source and destination paths.
  • Search permission is required for all parents of both paths.
  • Both paths be on the same mount point. On Android, applications are most likely to hit this restriction when attempting to copy between internal storage and an SD card.

As described in the documentation: http://developer.android.com/reference/java/io/File.html#renameTo(java.io.File)

Additionally, I would verify that the newFile path is what you expect it to be.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top