InputStream流已经关闭了,但是依旧无法delete文件或者文件夹,提示被JVM占用等

有时候流明明已经关闭了,但是还是无法删除文件或者文件夹,提示被JVM占用等

public void download(String sourceUrl, String targetPathFile) {
        URL url = null;
        //从网络上下载一张图片
        InputStream inputStream = null;
        OutputStream outputStream = null;
        //建立一个网络链接
        HttpURLConnection con = null;
        try {
            url = new URL(sourceUrl);
            con = (HttpURLConnection) url.openConnection();
            inputStream = con.getInputStream();
            outputStream = new FileOutputStream(new File(targetPathFile));
            int n = -1;
            byte b[] = new byte[1024];
            while ((n = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, n);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(inputStream!=null)
                inputStream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                if(outputStream!=null)
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
   }

这样的时候,通常可以这样解决:

                    System.gc();//在删除之前调用垃圾回收,这样jvm就不会占用文件了
                    try {
                        Thread.sleep(100);//我这边是这样,如果不休眠一会,依旧无法删除
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    boolean dirFile = FileUtils.deleteQuietly(new File(targetDirPath));
                    boolean zipFile = FileUtils.deleteQuietly(new File(targetZipPathFile));

 

你可能感兴趣的:(经验贴)