1. 内容是InputStream时:
String outputFile = "D:\\E\\ContentDownload1\\";
InputStream objectContent = list1.next().getContent();//文件内容
OutputStream outputStream = null;
//区分不同目录下相同的文件名, 所以增加了dir__做标记加以区分
File fr = new File(outputFile +sl[num]+"__"+ object.objectKey() +"_"+readMd5);
if (!fr.getParentFile().exists()) {//创建多层级目录
fr.getParentFile().mkdirs();
}
fr.createNewFile();//创建文件名
//创建输出流
outputStream = new FileOutputStream(fr);
//方式1: 当文件内容较大时容易出现java.lang.IndexOutOfBoundsException
int bytesWritten = 0;
int byteCount = 0;
byte[] bytes = new byte[1024]; //相当于一个顶量的水杯 每次读取1M的内容 缓冲区有大小限制
while ((byteCount = objectContent.read(bytes)) != -1) {
outputStream.write(bytes, bytesWritten, byteCount);//报异常Exception in thread “main“ java.lang.IndexOutOfBoundsException
bytesWritten += byteCount;
}
方式2:解决java.lang.IndexOutOfBoundsException
int len = -1;
byte[] bytes = new byte[2048];
while((len = objectContent.read(bytes)) != -1){
outputStream.write(bytes,0,len);
}
2. 当内容是byte类型时
String outputFile = "D:\\E\\ContentDownload2\\";
byte[] content = object.byteArray();
OutputStream outputStream = null;
File fr = new File(outputFile +sl[num]+"__"+ object.objectKey() +"_"+readMd5);
if (!fr.getParentFile().exists()) {//创建多层级目录
fr.getParentFile().mkdirs();
}
fr.createNewFile();//创建文件名
outputStream = new FileOutputStream(fr);
outputStream.write(content);
outputStream.close();
1735

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



