java对服务器文件操作、获取,删除,下载

java原生环境,不许引用其他文件
这次废话不多说,直接上代码
各个代码块之间的代码可以单独使用

远端获取文件

URL进行远端文件下载

本人亲写,绝对有效

/**
 * @author LM
 * @date 2021-11-03 - 9:40
 */
public class FileGainUtil {
    public static void main(String[] args) {
        FileGainUtil fileUtilLM = new FileGainUtil();
        String[] urls = new String[]{
                "https://img-blog.csdnimg.cn/img_convert/c8b0205e2b93a2c243b9c95541e83bbc.png",
                "https://img-blog.csdnimg.cn/img_convert/d645dc79a2565bcb940d237807666172.png",
                "https://img-blog.csdnimg.cn/img_convert/2b17c8c96f0d2ce292cae9b7ba68fb98.png",
                "http://wwwweeaazzcdfdsa"		//这个地址是错误的,用于测试
        };
        List<String> list = new ArrayList<>();
        //需要下载的文件地址集合,下载到本地的目录,文件后缀,存储下载过程中的错误信息
        //如果本地机器是linux系统 第二个参数可以直接是  /xx/xx/xxx		没有这个路径的话会先建
        fileUtilLM.actionAddFile(urls,"F:/cc/imama",".jpg",list);
        System.out.println(list);

		//z这个进行单个文件的下载
		String url = "https://img-blog.csdnimg.cn/img_convert/c8b0205e2b93a2c243b9c95541e83bbc.png";
		String path = "F://cs/image";
		String suffix = ".jpg";
		String name = "照片1";
		fileUtilLM.downLoadFile(url,path,suffix,name);
    }

    /**
     * 得到图片的二进制数据,以二进制封装得到数据,具有通用性
     * @param inStream
     * @return
     * @throws Exception
     */
    private byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while( (len=inStream.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    /***
     * @param urls          文件url路径数组
     * @param pathName      文件临时保存的路径
     * @param suffix        文件保存的后缀
     * @throws Exception
     */
    public boolean actionAddFile (String[] urls, String pathName, String suffix) {
        boolean temp = true;
        // 创建一个文件夹
        File file = new File(pathName);
        //如果存在的话进行删除存量数据
//        if (file.exists())
//            FileDeleteUtil.delFile(file);		//这个我下面一块的代码,没加入的话就注释掉

        file.mkdirs();
        try {
            //多个图片下载地址
            for(int i=0;i<urls.length;i++) {
                //文件下载到本地
                downLoadFile(urls[i],pathName,suffix,i+"");
            }

        } catch (Exception e) {
            e.printStackTrace();
            temp = false;
        }
        return temp;
    }

    /**
     * @param urlName       文件下载目标地址
     * @param pathName      文件保存的路径
     * @param suffix        文件后缀
     * @param name          保存的名称
     * */
    public void downLoadFile(String urlName,String pathName,String suffix,String name) throws Exception {
        URL url = new URL(urlName);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        InputStream inStream = conn.getInputStream();
        byte[] data = readInputStream(inStream);
        File imageFile = new File(pathName+"/"+name+suffix);
        FileOutputStream outStream = new FileOutputStream(imageFile);

        outStream.write(data);
        outStream.close();
        inStream.close();
    }


    /***
     * 入口函数
     * @param urls          文件url路径数组
     * @param pathName      文件临时保存的路径
     * @param suffix        文件保存的后缀
     * @param errors        文件抛出的错误
     */
    public void actionAddFile (String[] urls, String pathName, String suffix, List<String> errors) {

        // 创建一个文件夹
        File file = new File(pathName);
        //如果存在的话进行删除存量数据
//        if (file.exists())
//            FileDeleteUtil.delFile(file);		//本文下面部分的代码,需要使用请先加入

        file.mkdirs();
        for (int i = 0; i < urls.length; i++) {
            try {
                //文件下载到本地
                downLoadFile(urls[i],pathName,suffix,i+"");
            } catch (Exception e) {
                errors.add(pathName+"|"+urls[i]+ "==错误信息:" +e.toString());
            }
        }
    }
}

本地文件打包

打zip包

本人亲写,绝对有效

public class FileZipUtil {

    public static void main(String[] args) {
        //使用方法1
        FileZipUtil zc = new FileZipUtil("F:/Test.zip");
        zc.compress("F:/cc","F:/image");

        //使用方法2
        FileZipUtil zc2 = new FileZipUtil();
		zc2.setZipFile("F:/Test.zip");	//也可以是文件对象
		zc2.compress("F:/cc");
		zc2.compress("F:/cc/image/1.jpg");

		//这两个方法都会按照原本文件的格式,路径,模板进行打包就和直接在电脑上右键打包效果一样
		//并且Liunx也可以哦 亲测有效
    }
    
    static final int BUFFER = 8192;
    private File zipFile;
    public FileZipUtil() {}
    public FileZipUtil(String pathName) {
        zipFile = new File(pathName);
    }
    public void setZipFile(String pathName) {
        this.zipFile = new File(pathName);
    }
    public void setZipFile(File file) {
        this.zipFile = file;
    }

    /**
     * 这个是入口函数   pathName多个文件的路径
     * */
    public void compress(String... pathName) {
        ZipOutputStream out = null;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
            CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
                    new CRC32());
            out = new ZipOutputStream(cos);
            String basedir = "";
            for (int i=0;i<pathName.length;i++){
                compress(new File(pathName[i]), out, basedir);
            }
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public void compress(String srcPathName) {
        File file = new File(srcPathName);
        if (!file.exists())
            throw new RuntimeException(srcPathName + "不存在!");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
            CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
                    new CRC32());
            ZipOutputStream out = new ZipOutputStream(cos);
            String basedir = "";
            compress(file, out, basedir);
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void compress(File file, ZipOutputStream out, String basedir) {
        /* 判断是目录还是文件 */
        if (file.isDirectory()) {
            this.compressDirectory(file, out, basedir);
        } else {
            this.compressFile(file, out, basedir);
        }
    }

    /** 压缩一个目录 */
    private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
        if (!dir.exists())
            return;

        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            /* 递归 */
            compress(files[i], out, basedir + dir.getName() + "/");
        }
    }

    /** 压缩一个文件 */
    private void compressFile(File file, ZipOutputStream out, String basedir) {
        if (!file.exists()) {
            return;
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(
                    new FileInputStream(file));
            ZipEntry entry = new ZipEntry(basedir + file.getName());
            out.putNextEntry(entry);
            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            bis.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

文件下载到浏览器

http连接进行点击下载到浏览器

本人亲写,绝对有效
本代码所用技术SpringBoot
也可以用原生Sevlet技术等等…

  • 可以把 @GET和@Paht(“ssoDownload/file/{zipName}”) 这两个注释换成
    @RequestMapping("") …
  • 可以把@Context这个注释去掉
  • 可以把@JaxrsParameterDescribe这个注释去掉
  • @PathParam(“zipName”) 可以换成 SpringBoot常用的写法

1)服务器端代码

	@GET
    @Path("ssoDownload/file/{zipName}")
    public void ssoDownload(@Context HttpServletResponse response,
                             @JaxrsParameterDescribe("需要下载的文件路径+文件名(包括后缀) 一次只能下载一个")
                             @PathParam("zipName") String zipName) throws IOException {
        logger.info("============进行文件下载:是否删除原文件");

        OutputStream ous = null;
        InputStream ins = null;

        File file = new File(zipName);
        try {
            ins = new BufferedInputStream(new FileInputStream(file));
            response.reset();
            ous = new BufferedOutputStream(response.getOutputStream());
            
            byte[] bf = new byte[1024*8];
            int i = 0;
            while ((i = ins.read(bf)) != -1) {
                ous.write(i);
            }
            ous.flush();

            response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
            response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ins.close();
            ous.close();
        }
    }

2)浏览器端代码

//js代码
window.Open("上方的请求地址 如: localhost:80/ssoDownload/file/{zipName}");	//Open可能小写  问题不大  大概这样

本地文件操作

删除目录

/**
 * 这个类是专门用于删除文件夹的
 * @author LM
 * @date 2021-11-05 - 9:39
 */
public class FileDeleteUtil {
    /**
     * 进行指定目录的删除 或文件的删除
     *@param index    目录对象
     * */
    public static void delFile(File index){
        if (index.isDirectory()){
            File[] files = index.listFiles();
            for (File in: files) {
                delFile(in);
            }
        }
        index.delete();
    }

    /**
     * 进行多目录的删除
     * */
    public static void delFile(String... fileNames) {
        for (int i = 0; i < fileNames.length; i++) {
            delFile(new File(fileNames[i]));
        }
    }

    /**
     * 进行单目录的删除
     * */
    public static void delFile(String fileName) {
        delFile(new File(fileName));
    }
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值