美文网首页
BufferedOutputStream和FileOutputS

BufferedOutputStream和FileOutputS

作者: Cc_e789 | 来源:发表于2019-03-11 18:27 被阅读0次

    先贴个代码

    public static void downloadFile(String remoteFilePath, String localFilePath) {

    File remoteFile = new File(remoteFilePath);

    File localFile = new File(localFilePath);

    FileInputStream fis = null;

    FileOutputStream fos = null;

    BufferedInputStream bis = null;

    BufferedOutputStream bos = null;

    byte[] buffer=null;

    try {

    // 输入输出流对象

    fis = new FileInputStream(remoteFile);

    bis=new BufferedInputStream(fis);

    fos = new FileOutputStream(localFile);

    bos=new BufferedOutputStream(fos);

    System.out.println("源目录" + remoteFile.getPath());

    System.out.println("目标目录" + localFile.getPath());

    int len = 0;

    buffer = new byte[1024];

    while ((len = bis.read(buffer)) > -1) {

    System.out.println("len=" + len);

    // fos.write(buffer, 0, len);

    bos.write(buffer, 0, len);

    }

    bos.flush();

    System.out.println("最后一次len=" + len);

    System.out.println("下载成功");

    } catch (Exception e) {

    e.printStackTrace();

    } finally {

                if (fis != null) {

                    try {

                        fis.close();

                    System.out.println("fis.close");

                    } catch (IOException e) {

                        e.printStackTrace();

                    }

                }

                if (fos != null) {

                    try {

                        fos.close();

                    System.out.println("fos.close");

                    } catch (IOException e) {

                        e.printStackTrace();

                    }

                }if (bis != null) {

                    try {

                        bis.close();

                    System.out.println("bis.close");

                    } catch (IOException e) {

                        e.printStackTrace();

                    }

                }

                if (bos != null) {

                    try {

                    bos.close();

                    System.out.println("bos.close");

                    } catch (IOException e) {

                        e.printStackTrace();

                    }

                }

            }

    }

    上述代码中,特别要注意加粗的部分,

    当我fos.write(buffer, 0, len);执行后,直接fos.close();时,文件也能写到硬盘上;

    当我bos.write(buffer, 0, len);执行后,直接bos.close();时,文件却不能写到硬盘上,在bos.close();之前必须先bos.flush();

    查询API文档后发现

    FileOutputStream:

    BufferedOutputStream:

    在这里走了一点冤枉路,现作为提醒自己,写个记录。。。

    相关文章

      网友评论

          本文标题:BufferedOutputStream和FileOutputS

          本文链接:https://www.haomeiwen.com/subject/jqtipqtx.html