2

I have an image that I got from the user's album and I saved it in a folder.

here is the code:

   filename = "pippo.png";

             try {
                    ContextWrapper cw = new ContextWrapper(getApplicationContext());
                    File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);

                    // Create imageDir
                    File myPath = new File(directory,filename);

                    FileOutputStream out = new FileOutputStream(myPath);

                    theImage.compress(Bitmap.CompressFormat.PNG, 90, out);
                    out.flush();
                    out.close();
                    Log.d("Image","saved success");

                   picture =  directory.getAbsolutePath();

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("Image","saved failed");

                }

Then i read the image and change its name by that code:

if(comingIntent.hasExtra("FILEPATH"))
                {

                    filePath = comingIntent.getStringExtra("FILEPATH");
                    String filename = "pippo.png";

                    try {
                        File f = new File(filePath, filename);
                        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
                        playerImage.setImageBitmap(b);

                        File newfile = new File(filePath,username+".png");
                        f.renameTo(newfile);
                        Log.d("Image","first load succcess");

                    }
                    catch (FileNotFoundException e)
                    {
                        e.printStackTrace();
                        Log.d("Image","first load failed");

                    }

But then when I try to reload the image with its new name, I get a file not found exception, that's the code:

try {
       File f = new File(filePath, username+".png");
       Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
       playerImage.setImageBitmap(b);

       Log.d("Image","second load succcess");  }

 catch (FileNotFoundException e)
       {
         e.printStackTrace();
         Log.d("Image","second load failed"); }

That's the Log error:

08-09 20:23:50.730 15052-15052/? W/System.err: java.io.FileNotFoundException: lol1.png: open failed: ENOENT (No such file or directory) 08-09 20:23:50.743 15052-15052/? W/System.err:
at libcore.io.IoBridge.open(IoBridge.java:452) at java.io.FileInputStream.(FileInputStream.java:76) at com.example.abzo.socsoc.PlayerHomePage.onCreate(PlayerHomePage.java:103) at android.app.Activity.performCreate(Activity.java:6285) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2414) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2521) at android.app.ActivityThread.access$900(ActivityThread.java:150) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1383) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5517) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory) at libcore.io.Posix.open(Native Method) at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186) at libcore.io.IoBridge.open(IoBridge.java:438) ... 14 more 08-09 20:23:50.744 15052-15052/? D/Image: second load failed

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 1
    Have you determined that the file is actually renamed by your code in internal storage? Although this does not appear to be your problem looking at the code you posted, I have had issues with **renameTo()** before when there are edits in progress. And can you provide the log? – ViaTech Aug 09 '18 at 18:42
  • @ViaTech that's the weird part ,the folder "imageDir" that i created is not in data>data>my app ,i cant find it ,even though it read the image from the first load ..and sure one sec. – Abdelrahman Hashim Aug 09 '18 at 18:50
  • @ViaTech that's the path /data/user/0/com.example.abzo.socsoc/app_imageDir , but how to access it? ,i cant see user in data when i use Device explorer – Abdelrahman Hashim Aug 09 '18 at 18:59
  • Hmm.. the code you provided above does not seem complete so I am not able to recreate your issue directly (at least yet), but yeah since the error you are getting is **No such file or directory**, you are attempting to open a file that does not exist. This can happen for a few reasons which is easy to check if you actually have access to the directory from the Explorer, but since you don't you will need to troubleshoot the path using logs. In your second code snippet set **filePath = f.getAbsolutePath()** after the rename and **Log.d("Image","first load succcess");** Does that do anything? – ViaTech Aug 09 '18 at 19:33
  • @ViaTech it didnt rename it , i checked it ..so there was no such file, why it didnt rename it ? – Abdelrahman Hashim Aug 10 '18 at 09:44
  • I am not certain in your specific situation why the rename is failing because, as I said, this is not your full code, but I have taken the code you have posted and provided a solution that shows it works in the **logs**, please check my post. **Note** in my solution I am not actually grabbing images from the user's gallery or album, I am just showing how to complete the rename successfully based on the code you provided – ViaTech Aug 10 '18 at 15:01

2 Answers2

0

As we discussed in the comments, I believe your renameTo() is not working because of some type of hold on the file, but you did not post your full code so I cannot be completely sure.

With the code you provided, I have created a MainActivity that accomplishes a rename of the file you noted that was stored in Internal Storage (i.e. pippo.png). The successful rename is proved in the debug logs when you run the Activity.

Note: In my solution below I am just creating Files and placing them where you said they are supposed to go to provide you an answer of how renameTo() should/can be used in your app, I am not actually working with images as you did not provide me with your code that you use to access the images. I'm sure you realize this, but you will need to be sure the image you are working with is being selected correctly by the user and the path is accurate for my example to work when you plug it into your real application.

public class MainActivity extends AppCompatActivity {

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

        String imageFilename = "pippo.png";
        //example username, I am not sure how you get this info
        String exampleUsername = "user1";   

        try {
            ContextWrapper cw = new ContextWrapper(getApplicationContext());
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            //check that we are good here...
            if(directory.exists())
                Log.d("ImageTAG", "'imageDir' exists");

            // create imageDir
            File completeImagePath = new File(directory, imageFilename);

            //write file
            FileOutputStream out = new FileOutputStream(completeImagePath);

            out.flush();
            out.close();

            //check to ensure complete image path exists... it should
            if(completeImagePath.exists())
                Log.d("ImageTAG", "'completeImagePath' exists");

            //show full path on device
            Log.d("ImageTAG", "Image saved success, complete Image Path: " +
                    completeImagePath.getAbsolutePath());

            //redeclaration of file here is not needed, but added for clarity
            File from = new File(completeImagePath.getAbsolutePath());
            //what you are renaming the file to
            File to = new File(directory, exampleUsername + ".png");
            //now rename
            Boolean success = from.renameTo(to);

            Log.d("ImageTAG", "Successful Rename: "+success.toString()+"| File is now named: "+to.getPath());

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("ImageTAG","saved failed");
        }

    }
}
ViaTech
  • 2,143
  • 1
  • 16
  • 51
0

In Kotlin, This way is the simplest one:

try {
                val dir =context.getDir("imageDir", AppCompatActivity.MODE_PRIVATE)
                if (dir.exists()) {
                    val from = File(dir, "old_name.png")
                    val to = File(dir, "new_Name.png")
                    if (from.exists()) from.renameTo(to)
                }
    } catch (e: IOException) {
                e.printStackTrace()
               
            }catch (e:NullPointerException){
                e.printStackTrace()
              
            }
Mori
  • 2,653
  • 18
  • 24