文件操作

一:删除文件

/**
     *递归删除文件目录下的所有文件
     * @param file 要删除的文件目录
     * @return 如果成功,返回true.
     */
    public static boolean deleteDir(File file){
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for(int i=0; i<files.length; i++){
                deleteDir(files[i]);
            }
        }
        file.delete();
        return true;
    }

 二:下载图片到本地

public static void download(String urlString, String filename,String savePath) throws Exception {  
        // 构造URL  
        URL url = new URL(urlString);  
        // 打开连接  
        URLConnection con = url.openConnection();  
        //设置请求超时为5s  
        con.setConnectTimeout(5*1000);  
        // 输入流  
        InputStream is = con.getInputStream();  
      
        // 1K的数据缓冲  
        byte[] bs = new byte[1024];  
        // 读取到的数据长度  
        int len;  
        // 输出的文件流  
       File sf=new File(savePath);  
       if(!sf.exists()){  
           sf.mkdirs();  
       }  
       OutputStream os = new FileOutputStream(sf.getPath()+"\"+filename);  
        // 开始读取  
        while ((len = is.read(bs)) != -1) {  
          os.write(bs, 0, len);  
        }  
        // 完毕,关闭所有链接  
        os.close();  
        is.close();  
    }   

 三:下载文件到本地

   File file = new File(path);  // path是根据路径和文件名拼接出来的
    String filename = file.getName();// 获取文件名称
    InputStream fis = new BufferedInputStream(new FileInputStream(path));
    byte[] buffer = new byte[fis.available()];
    fis.read(buffer);
    fis.close();
    response.reset();
    // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
    response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
    response.addHeader("Content-Length", "" + file.length());
    OutputStream os = new BufferedOutputStream(response.getOutputStream());
    response.setContentType("application/octet-stream");
    os.write(buffer);// 输出文件
    os.flush();
    os.close();
原文地址:https://www.cnblogs.com/fdzfd/p/5848153.html