java - 如何将图像文件从图库移动到另一个文件夹

标签 java android

我想从图库中获取图像并将其保存到另一个文件夹。我尝试使用代码

private void copyFile(File inputPath, File outputPath){
        try{

                InputStream in = null;
                OutputStream out = null;
                try {
                    in = new FileInputStream(inputPath);
                    out = new FileOutputStream(outputPath);

                    byte[] buffer = new byte[1024];
                    int read;
                    while ((read = in.read(buffer)) != -1) {
                        out.write(buffer, 0, read);
                    }
                    in.close();
                    in = null;

                    // write the output file (You have now copied the file)
                    out.flush();
                    out.close();
                    out = null;

                    Log.d("Copied file to ", outputPath.toString());

                } catch (FileNotFoundException fnfe1) {
                    Log.d("Tag",fnfe1.getMessage());
                } catch (Exception e) {
                    Log.d("tag", e.getMessage());
                }

        }catch (Exception e){
            e.printStackTrace();
        }
}

最佳答案

我建议使用 try-with-resources 和 java 8 Files/Path api:

private void copyFile(File inputPath, File outputPath){
 try (FileOutputStream fos = new FileOutputStream(outputPath)) {

     Files.copy(inputPath.toPath(), fos);
     Log.d("Copied file to ", outputPath.toString());

  } catch (FileNotFoundException fnfe1) {
     Log.d("Tag",fnfe1.getMessage());
  } catch (Exception e) {
     Log.d("tag", e.getMessage());
  }
}

关于java - 如何将图像文件从图库移动到另一个文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57426598/

相关文章:

java - 从给定的url获取域名

java - Xpath是正确的仍然没有得到这样的元素: Unable to locate element

java - 如何动态计算 session 超时时间?

android - Recyclerview 和 Cardview 我有设计问题

android - 有没有办法发现 android 手机的电池不再可用,我们需要以编程方式更改它?

android - 如何在 Android Studio 中对齐 XML 代码?

java - 什么是NullPointerException,我该如何解决?

java - 为什么我的数据库仅在前两个 jsp 表单提交时更新成功?

android - JSON 在 GSON 中解析的初始大写 key 问题

android - 如何将drawableLeft对齐到顶部而不是在android TextView中居中?