文件操作—文件拷贝

一、错误 代码

public class Job20180131_error {

    public static void copyFile(String ofilePath, String dfilePath)  {
        if (TextUtils.isEmpty(ofilePath) || TextUtils.isEmpty(dfilePath)) {
            System.out.println("ofilePath/dfilePath can not be null/\"\";");
            return;
        }
        File ofile = new File(ofilePath);
        if (!ofile.exists()) {
            System.out.println(ofilePath + " can not found");
        }

        File dfile = new File(dfilePath);
        if (dfile.exists()) {
            dfile.delete();
        } else {
            boolean result = dfile.mkdirs();
            System.out.println("dfile.mkdirs() = " + result);
        }

        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {

            fis = new FileInputStream(ofile);
            // @param size 通过查看源码可知,默认缓冲大小为8192,这里设置10k
            bis = new BufferedInputStream(fis, 10 * 1024);

            // @param appednd 如果是true,那么字节将被写入到文件的末尾,而不是开始
            fos = new FileOutputStream(dfile, false);
            // @param size 通过查看源码可知,默认缓冲大小为8192,这里设置10k
            bos = new BufferedOutputStream(fos, 10 * 1024);

            byte[] obytes = new byte[4 * 1024];
            int pos = -1;
            while ((pos = bis.read(obytes)) != -1) {
                // 通过查看源码可知,当obytes的size>=缓冲区大小,
                // 就会使用OutputStream的write()方法,从而无法体现出BufferedOutputStream的优势
                // 所以obytes大小这只为4 * 1024
                bos.write(obytes, 0, pos); // 这里差不多2次循环 flushBuffer() 一次
            }
            bos.flush(); // 将缓冲区的剩余数据写入文件

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

        } finally {
            try {
                // 关闭所有文件引用
                if (bos != null) { bos.close(); }
                if (bis != null) { bis.close(); }
                if (fos != null) { fos.close(); }
                if (fis != null) { fis.close(); }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main() {
        String ofile = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "Download/img1.png";
        String dfile = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "AAAA-1/imgCopy1.png";
        copyFile(ofile, dfile);
    }

}

错误日志

01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err: java.io.FileNotFoundException: /storage/emulated/0/AAAA-1/imgCopy1.png: open failed: EISDIR (Is a directory)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:409)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at java.io.FileOutputStream.(FileOutputStream.java:88)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at com.ktln.must.java.job.Job20180131_error.copyFile(Job20180131_error.java:48)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at com.ktln.must.java.job.Job20180131_error.main(Job20180131_error.java:84)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at com.ktln.must.MainActivity$onCreate$1.onClick(MainActivity.kt:29)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at android.view.View.performClick(View.java:4480)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at android.view.View$PerformClick.run(View.java:18686)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at android.os.Handler.handleCallback(Handler.java:733)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at android.os.Looper.loop(Looper.java:157)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5872)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at dalvik.system.NativeStart.main(Native Method)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err: Caused by: libcore.io.ErrnoException: open failed: EISDIR (Is a directory)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at libcore.io.Posix.open(Native Method)
01-31 15:40:26.605 28686-28686/com.ktln.must W/System.err:     at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
01-31 15:40:26.615 28686-28686/com.ktln.must W/System.err:     at libcore.io.IoBridge.open(IoBridge.java:393)
01-31 15:40:26.615 28686-28686/com.ktln.must W/System.err:  ... 15 more

第一次运行会出现上面的错误,第二次运行是正常!!!

二、正确 代码

public class Job20180131 {

    public static void copyFile(String ofilePath, String dfilePathDir, String dfilePath)  {
        if (TextUtils.isEmpty(ofilePath)
                || TextUtils.isEmpty(dfilePathDir)
                || TextUtils.isEmpty(dfilePath)) {
            System.out.println("ofilePath/dfilePathDir/dfilePath can not be null/\"\";");
            return;
        }
        File ofile = new File(ofilePath);
        if (!ofile.exists()) {
            System.out.println(ofilePath + " can not found");
        }

        // 不存在路径,创建路径
        File dfileDir = new File(dfilePathDir);
        if (!dfileDir.exists()) { dfileDir.mkdirs(); }

        // 存在文件删除
        File dfile = new File(dfilePathDir, dfilePath);
//      File dfile = new File(dfilePathDir + File.separator + dfilePath); // 这样也是正确的
        if (dfile.exists()) { dfile.delete(); }

        FileInputStream fis = null;
        BufferedInputStream bis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fis = new FileInputStream(ofile);
            // @param size 通过查看源码可知,默认缓冲大小为8192,这里设置10k
            bis = new BufferedInputStream(fis, 10 * 1024);

            // @param appednd 如果是true,那么字节将被写入到文件的末尾,而不是开始
            fos = new FileOutputStream(dfile, false);
            // @param size 通过查看源码可知,默认缓冲大小为8192,这里设置10k
            bos = new BufferedOutputStream(fos, 10 * 1024);

            byte[] obytes = new byte[4 * 1024];
            int pos = -1;
            while ((pos = bis.read(obytes)) != -1) {
                // 通过查看源码可知,当obytes的size>=缓冲区大小,
                // 就会使用OutputStream的write()方法,从而无法体现出BufferedOutputStream的优势
                // 所以obytes大小这只为4 * 1024
                bos.write(obytes, 0, pos); // 这里差不多2次循环 flushBuffer() 一次
            }
            bos.flush(); // 将缓冲区的剩余数据写入文件

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

        } finally {
            try {
                // 关闭所有文件引用
                if (bos != null) { bos.close(); }
                if (bis != null) { bis.close(); }
                if (fos != null) { fos.close(); }
                if (fis != null) { fis.close(); }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main() {
        String ofile = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "Download/img1.png";

        String dfilePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + File.separator + "AAAA-10";

        String dfile =  "imgCopy1.png";

        copyFile(ofile, dfilePath, dfile);
    }

}

三、总结

  • 错误代码File dfile = new File(dfilePath);这里的dfilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "AAAA-1/imgCopy1.png"是包含文件夹文件;在第一次运行时,实际只是创建了文件夹,file指向是一个文件夹;第二次运行时,由于文件夹已经存在,这时候的file指向才是一个文件;
  • 正确代码File dfileDir = new File(dfilePathDir);这个dfilePathDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "AAAA-10";然后调用dfileDir.mkdirs();创建出文件路径,再用路径和文件名构造一个fileFile dfile = new File(dfilePathDir, dfilePath);,使用这个file进行文件写操作。

四、疑问!!!

虽然我找到正确写入的代码,但对这个问题本身还是有些迷糊,我试过在dfilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "AAAA-1/imgCopy1.png";下,先创建一个File file1 = new File(dfilePath); 进行file1.mkdirs();,然后再创建一个File file2 = new File(dfilePath);进行写操作,但还是出现上面的错误信息。按照之前的理解,file1可以保证文件路径的存在,file2应该可以正常写操作,但实际是错误的,知道答案的请留言给我!!万分感谢!!



ps: 我找过FileOutputStream的源码,但跟踪到private native void open0(String name, boolean append) throws FileNotFoundException;时,就找不到后文了,无语只能到此暂时放下!!

你可能感兴趣的:(文件操作—文件拷贝)