如何在内部存储中重命名文件? [英] How to rename a file in internal Storage?

查看:106
本文介绍了如何在内部存储中重命名文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张从用户相册中获得的图像,并将其保存在一个文件夹中.

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

下面是代码:

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

那是Log错误:

08-09 20:23:50.730 15052-15052/?W/System.err:java.io.FileNotFoundException:lol1.png:打开失败:ENOENT(否文件或目录)08-09 20:23:50.743 15052-15052/?W/System.err:
在libcore.io.IoBridge.open(IoBridge.java:452)在java.io.FileInputStream((FileInputStream.java:76)在com.example.abzo.socsoc.PlayerHomePage.onCreate(PlayerHomePage.java:103)在android.app.Activity.performCreate(Activity.java:6285)在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2414)在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2521)在android.app.ActivityThread.access $ 900(ActivityThread.java:150)在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1383)在android.os.Handler.dispatchMessage(Handler.java:102)在android.os.Looper.loop(Looper.java:148)在android.app.ActivityThread.main(ActivityThread.java:5517)在java.lang.reflect.Method.invoke(本机方法)在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)引起原因:android.system.ErrnoException:打开失败:ENOENT(无此类文件或目录)在libcore.io.Posix.open(本机方法)在libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)在libcore.io.IoBridge.open(IoBridge.java:438)...还有14个08-09 20:23:50.744 15052-15052/?D/图像:第二次加载失败

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

推荐答案

正如我们在评论中所讨论的,我认为您的 renameTo()无法正常工作,因为文件具有某种保留类型,但是您没有发布完整的代码,所以我不能完全确定.

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.

使用您提供的代码,我创建了一个 MainActivity ,用于对您存储在内部存储(即pippo.png)中的文件进行重命名.当您运行Activity时,将在调试日志中证明成功的重命名.

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.

注意::在下面的解决方案中,我只是创建文件并将其放置在您认为应该去的地方,以为您提供有关 renameTo()应该如何使用的答案/可以在您的应用程序中使用,因为您没有向我提供用于访问图像的代码,因此我实际上并未使用图像.我相信您已经意识到了这一点,但是您需要确保用户正确选择了正在使用的图像,并且在将其插入到实际应用程序中时,路径对于我的示例来说是正确的.

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

    }
}

这篇关于如何在内部存储中重命名文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆