测试用例如下, 所有数据是字节传输,可以下载任务文件(有权限)
@Test
public void test() throws Exception{
// 获取媒体文件的输入流(读取文件)
String mediaFileUrl = "http://img10.360buyimg.com/imgzone/jfs/t1/64129/40/1652/208494/5d0062fdE5b875f8f/1336f14c55be3ef8.jpg";
URL mediaUrl = new URL(mediaFileUrl);
HttpURLConnection mediaConn = (HttpURLConnection) mediaUrl.openConnection();
mediaConn.setDoOutput(true);
mediaConn.setRequestMethod("GET");
// 从请求头中获取内容类型
String contentType = mediaConn.getHeaderField("Content-Type");
// 根据内容类型判断文件扩展名
String fileExt = CommonUtils.getFileExt(contentType);
BufferedInputStream bis = new BufferedInputStream(mediaConn.getInputStream());
String file = "D:/test/download/" + UUID.randomUUID().toString() + "." + fileExt;
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
byte[] buf = new byte[8192];
int size = 0;
while ((size = bis.read(buf)) != -1) {
// 将媒体文件写到输出流
outputStream.write(buf, 0, size);
}
outputStream.close();
bis.close();
mediaConn.disconnect();
System.out.println("Fin");
}
文件byte实际大小,并一次性输出流
@Test
public void test3() throws Exception{
// 获取媒体文件的输入流(读取文件)
String mediaFileUrl = "http://img10.360buyimg.com/imgzone/jfs/t1/40966/18/6468/250346/5d0062fdE2ad7d274/8f71146ab69ffa56.jpg";
URL mediaUrl = new URL(mediaFileUrl);
HttpURLConnection mediaConn = (HttpURLConnection) mediaUrl.openConnection();
mediaConn.setDoOutput(true);
mediaConn.setRequestMethod("GET");
// int length = mediaConn.getContentLength();
// System.out.println("getContentLengthLong:" + mediaConn.getContentLengthLong());
// System.out.println("getContentLength:" + length);
// 从请求头中获取内容类型
String contentType = mediaConn.getHeaderField("Content-Type");
// 根据内容类型判断文件扩展名
String fileExt = CommonUtils.getFileExt(contentType);
BufferedInputStream bis = new BufferedInputStream(mediaConn.getInputStream());
String file = "D:/test/download-64/" + UUID.randomUUID().toString() + "." + fileExt;
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
byte[] buf = new byte[8192];
int size = 0;
ByteBuffer byteBuffer = ByteBuffer.allocate(250346*3);
while ((size = bis.read(buf)) != -1) {
// 将媒体文件写到输出流
outputStream.write(buf, 0, size);
byteBuffer.put(buf, 0, size);
}
System.out.println("byteBuffer position2 limit:" + byteBuffer.limit());
byteBuffer.flip();
byte[] target = new byte[byteBuffer.limit()];
byteBuffer.get(target);
System.out.println("byteBuffer position end:" + byteBuffer.position());
System.out.println("target length end:" + target.length);
String file2 = "D:/test/download-64/" + UUID.randomUUID().toString() + "PPP." + fileExt;
OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(file2));
outputStream2.write(target);
outputStream2.close();
outputStream.close();
bis.close();
mediaConn.disconnect();
System.out.println("Fin");
}
802

被折叠的 条评论
为什么被折叠?



