java - 如何重命名内部存储中的文件?

标签 java android filenotfoundexception internal-storage

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

代码如下:

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

                }

然后我读取图像并通过该代码更改其名称:

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

                    }

但是当我尝试用它的新名称重新加载图像时,我得到一个找不到文件的异常,这就是代码:

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

这是日志错误:

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() 因某种类型的文件保留而无法正常工作,但您没有发布完整的代码,因此我不能完全确定.

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

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

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

    }
}

关于java - 如何重命名内部存储中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51773785/

相关文章:

c# - "Could not load file or assembly ' XXX.YYY ' or one of its dependencies. The system cannot find the file specified."

android - 在 libgdx 中管理桌面和设备版本之间的 Assets

java - 在 Map Reduce 作业中使用多线程

java - if(pause == null) { 不起作用

java - 在 android 4.4 中永久禁用我的应用程序的通知栏

android - 将多个 firebase 目录中的所有帖子显示到 recyclerView 中

java - 由 Apache POI 创建时 excel 文件中的兼容模式

java - Java中如何将变量从一个JFrame传递到多个JFrame?

android - 将自定义对象写入 Firebase 数据库

java - 从 ICEfaces 中的 build.properties 获取值时出现问题