import java.io.*;
import java.net.URL;
import java.util.zip.GZIPOutputStream;
/**
* Created with IntelliJ IDEA.
* User: smy
* Date: 2020/3/17
* Time: 10:37
* Description: No Description
*/
public class FileUtils {
/**
* 获取文件、二进制byte数组
* @param arg
* @return
*/
public static byte[] getFileByteArray(String arg){
ByteArrayOutputStream byteArr = new ByteArrayOutputStream();
try {
URL url = new URL(arg);
InputStream in = url.openStream();
byte[] buf = new byte[1024];
int length = 0;
while((length = in.read(buf)) != -1){
byteArr.write(buf,0,length);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return byteArr.toByteArray();
}
/**
* 获取网络文件并写入本地 测试用
* @param arg
* @return
*/
public static void getFileByteArrAndWrite(String arg){
byte[] byteArray = getFileByteArray(arg);
byte[] bytes = compress(byteArray);
//String json = new String(Base64.encodeBase64(bytes));
File file = new File("H://new.xlsx");
try {
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(byteArray);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] compress(byte[] data) {
//System.out.println("before:" + data.length);
GZIPOutputStream gzip = null ;
ByteArrayOutputStream baos = null ;
byte[] newData = null ;
try {
baos = new ByteArrayOutputStream() ;
gzip = new GZIPOutputStream(baos);
gzip.write(data);
gzip.finish();
gzip.flush();
newData = baos.toByteArray() ;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
gzip.close();
baos.close() ;
} catch (IOException e) {
e.printStackTrace();
}
}
//System.out.println("after:" + newData.length);
return newData ;
}
public static void main(String[] args) {
getFileByteArrAndWrite("http://10.0.6.44/upload/public/0/4d90b2ad1a1249369a2888f07bffa976@付款计划-业务版 (2).xlsx");
//getFileByteArrAndWrite("http://10.0.6.44/upload/public/0/889a2873ccf54431a1053f9b7fc99f0e@9df1692fe9b1dcb2b4fa55d380e1be64.jpg");
}
}