问题背景:我们项目开发的时候,经常会读取文件,如果文件在本服务器,则直接用new File() 读取即可,但是有时候需要远程读取文件,比如读取分布式存储服务器的内容或者是别人家的图片资源,这个时候new File就无法满足要求了。
下面提供列出获取远程文件和本地文件的方式
1、获取远程文件
如图片路径为 https://file.lsjlt.com/upload/f/202308/17/culo3qxcgtu.jpg
import java.net.HttpURLConnection;import java.io.*;import java.net.URL;import java.net.URLConnection;public byte[] getFile(String filePath) { int HttpResult; // 服务器返回的状态 byte[] bytes = new byte[204800]; //设置数组大小 try { URL url =new URL(filePath); // 创建URL URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码 urlconn.connect(); HttpURLConnection httpconn =(HttpURLConnection)urlconn; HttpResult = httpconn.getResponseCode(); if(HttpResult != HttpURLConnection.HTTP_OK) { log.error("获取文件失败,无法连接到文件资源") } else { int filesize = urlconn.getContentLength(); // 取数据长度 log.info("取数据长度:{}",filesize) urlconn.getInputStream(); InputStream inputStream = urlconn.getInputStream();//如果这里只需要返回stream,则直接返回 不需要转byte[] ByteArrayOutputStream swapStream = new ByteArrayOutputStream(); int ch; while ((ch = inputStream.read()) != -1) { swapStream.write(ch); } bytes = swapStream.toByteArray(); } log.info("文件大小,length:{}",bytes.length); } catch (Exception e) { log.error("获取文件异常,e:{}",e); } return bytes; }
获取本地文件
File file = new File("/resource/static/sdsadc12.jpg");InputStream in = null;try {// 一次读多个字节byte[] tempbytes = new byte[100];int byteread = 0;in = new FileInputStream(file);// 读入多个字节到字节数组中,byteread为一次读入的字节数while ((byteread = in.read(tempbytes)) != -1) {System.out.write(tempbytes, 0, byteread);}log.info("文件大小:{}"+file.length());} catch (Exception ee) {log.error("异常:{}",ee);} finally {if (in != null) {try {in.close();} catch (IOException e1) {}}}
来源地址:https://blog.csdn.net/qq_32590535/article/details/131339229