java后台远程调用获取文件

一、模拟本地服务为文件服务器(两种提供方式):假设本地文件为服务器,提供文件获取服务

方法一:直接将输出流放入response里面作为响应

@RequestMapping(value = "/getUrlDownload",method = RequestMethod.GET)
    @ResponseBody
    public void getUrlDownload(HttpServletResponse response) {
        String url = "C:\\user.zip";
        File file = new File(url);
        //判断文件是否存在如果不存在就进行异常处理
        if (!(file.exists() && file.canRead())) {
            System.out.println("文件不存在");
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

方法二:将输入流放入ResponseEntity的body里面,并做返回

String separator = File.separator;

    @RequestMapping(value = "/download", method = RequestMethod.GET, produces ="application/json;charset=UTF-8")
    @ResponseBody
    public ResponseEntity<InputStreamResource> download() {

        String newName = "2";
        String route = "download" + File.separator + "templates" + File.separator;
        String path = null;
        ResponseEntity<InputStreamResource> response = null;
        try {
            path = "download" + separator + "bst.zip";
            ClassPathResource classPathResource = new ClassPathResource(path);
            InputStream inputStream = classPathResource.getInputStream();
            response = ResponseEntity.ok()
                    .body(new InputStreamResource(inputStream));
        } catch (FileNotFoundException e1) {
            System.out.println(e1.getMessage());
//            log.error("找不到指定的文件", e1);
        } catch (IOException e) {
            System.out.println(e.getMessage());
//            log.error("获取不到文件流", e);
        }

        return response;
    }

以上两种方式皆可做文件服务器,提供给其他服务获取文件,这里注意与文件下载并不一样,都是以流的形式返回或者响应。而文件下载是将服务器的文件下载到本地,接下来演示远程文件下载代码。

二、远程获取文件(两种方式):

方式一:RestTemplate 获取,如下代码:

 @RequestMapping(value = "/getf", method = RequestMethod.GET, produces ="application/json;charset=UTF-8")
    @ResponseBody
    public void getf() throws URISyntaxException {
        String url = "http://localhost:8888/file/download";
        RequestEntity build = RequestEntity.get(new URI(url)).build();
        RestTemplate restTemplate  =new RestTemplate();
        ResponseEntity<byte[]> exchange = restTemplate.exchange(build, byte[].class);
        byte[] body = exchange.getBody();

        String fileName = "xxxx.zip";
        String filePath = "src/main/resources/templates/";
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if(!dir.exists() && !dir.isDirectory()){//判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(body);
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

方式二:URL获取,代码如下:

  @RequestMapping(value = "/getFile", method = RequestMethod.GET, produces ="application/json;charset=UTF-8")
    @ResponseBody
    public void getFile() {
        String filePath = "http://localhost:8888/file/getUrlDownload";
        //定义文件名
        String fileName = "111.zip";

//定义要保存的文件路径
        String savePath = "/resources/templates/"+fileName;
        File file = new File(savePath);

//如果文件目录不出在则创建目录 *getParentFile()*
        if (!file.getParentFile().exists()) {
            //判断文件目录是否存在
            file.getParentFile().mkdirs();//创建目录
        }

        try {
            URL url = new URL(filePath);
            //字节输入流
            InputStream is = url.openStream();
            //字节流转字符流

            DataInputStream dataInputStream = new DataInputStream(is);
                                                    转化流
            FileOutputStream fileOutputStream = new FileOutputStream(file);

            //使用char 数组传输    -----字节流byte数组
            byte[] chs = new byte[1024];
            //标记
            int len = 0;
            while ((len = dataInputStream.read(chs)) != -1) {
                // read() 方法,读取输入流的下一个字节,返回一个0-255之间的int类型整数。如果到达流的末端,返回-1

                fileOutputStream.write(chs,0,len);
            }
            fileOutputStream.close();
            dataInputStream.close();

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

        }
    }

以上两种皆可远程获取到文件服务器的文件,只是方式不一样,但是获取本质都是以流的形式获取到,转换为byte[] 数组,最终写出来。方法二中有一个注意点,write方法重载有三个write(int a)、write(byte[] by,int begin,int end)、write(byte[] by),这里一般用write(byte[] by,int begin,int end),可保证下载文件正常打开,zip、rar文件打开时不会遇到:不可预测的文件尾部 ,这样的异常信息,其次是在以上方式中并没有添加中文乱码情况,可做补充。

ok,本篇文章,只做记录,暂时留用,后期有更好方法再更,希望有看到的同僚提供更多意见,谢谢!

 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

焱墩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值