个人学习笔记 不知道文件是什么格式类型的
public static void downLoadFile(String httpurl ) throws Exception{
URL url = new URL(httpurl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
InputStream inputStream = conn.getInputStream();
String fileName = httpurl.split("\\?fileId")[1];
System.out.println("fileName"+fileName);
byte[] b = new byte[3];
int a = inputStream.read(b,0,b.length);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(b, 0, a);
byte[] getData = readInputStream(inputStream,bos);
System.out.println("byte b = "+JSON.toJSONString(b));
String xxx = bytesToHexString(b);
xxx = xxx.toUpperCase();
System.out.println("头文件是:" + xxx);
String ooo = checkType(xxx);
System.out.println("后缀名是:" + ooo);
if(!"".equals(ooo)){
File saveDir = new File("/"+File.separator+"tmp"+ File.separator+"wwTestApi"+ File.separator );
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+File.separator+fileName+ooo);
System.out.println("qian="+file.length());
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
fos.flush();
System.out.println("hou="+file.length());
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}
System.out.println("info:"+url+" download success");
}
}
public static byte[] readInputStream(InputStream inputStream,ByteArrayOutputStream bos) throws IOException {
byte[] buffer = new byte[1024];
byte[] b = new byte[3];
int len = 0;
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.flush();
bos.close();
return bos.toByteArray();
}
public static String checkType(String xxxx) {
switch (xxxx) {
case "FFD8FF": return ".jpg";
case "89504E": return ".png";
case "255044": return ".pdf";
default:
System.out.println(xxxx);
return "";
}
}
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
|