【问题标题】:Copying file and saving with different file name复制文件并使用不同的文件名保存
【发布时间】:2016-01-14 16:19:14
【问题描述】:

我正在尝试在 android 中复制文件。我有文件的文件路径。我想将它复制到另一个具有不同文件名的文件夹。我正在使用下面的代码,但它不起作用。我的文件是视频文件. 我得到错误-

/storage/emulated/0/testcopy.mp4: open failed: EISDIR (Is a directory)

下面是我的代码

 File source=new File(filepath);
    File destination=new File(Environment.getExternalStorageDirectory()+ "/testcopy.mp4");
    copyFile(source.getAbsolutePath(),destination.getAbsolutePath());



private void copyFile(String inputPath, String outputPath) {

        InputStream in = null;
        OutputStream out = null;
        try {

            //create output directory if it doesn't exist
            File dir = new File (outputPath);
            if (!dir.exists())
            {
                dir.mkdirs();
            }


            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;

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

    }

【问题讨论】:

    标签: android file directory file-copying


    【解决方案1】:

    您在这里创建一个名为“/storage/emulated/0/testcopy.mp4”的目录

    //create output directory if it doesn't exist
    File dir = new File (outputPath);
    if (!dir.exists())
    {
        dir.mkdirs();
    }
    

    试试这个代码

    //create output directory if it doesn't exist
    File dir = (new File (outputPath)).getParentFile();
    if (!dir.exists())
    {
        dir.mkdirs();
    }
    

    【讨论】:

      【解决方案2】:

      他们的主要问题是您正在尝试编写作为目录的文件。为避免此异常,请先创建目录,然后写入文件:

          File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
          // creating a new folder if doesn't exist
          boolean success = folder.exists() || folder.mkdirs();
          File file = new File(folder, "filename.mp4");
      
          try {
              if (!file.exists() && success) file.createNewFile();
              ...
              byte[] buffer = new byte[1024];
              int read;
              while ((read = in.read(buffer)) != -1) {
                  out.write(buffer, 0, read);
              }
              ...
          }catch (IOException e){
              e.printStackTrace();
          }
      

      【讨论】:

        猜你喜欢
        • 2020-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-16
        • 1970-01-01
        • 2011-12-04
        • 1970-01-01
        相关资源
        最近更新 更多