Springboot分片上传
public static void main(String[] args) throws IOException {
File sourceFile = new File("D:\\44.mp4");
String chunkFolder = "D:\\IDM\\videos\\chunks\\";
File f = new File(chunkFolder);
if (!f.exists()){
f.mkdirs();
}
long shareSize = 1024 * 1024 * 10; // 分片的大小,单位为字节
System.out.println("分片大小: " shareSize);
try (RandomAccessFile randomAccessFileReader = new RandomAccessFile(sourceFile, "r");FileChannel fileChannelReader = randomAccessFileReader.getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
long total = (long) Math.ceil(sourceFile.length() * 1.0 / shareSize);
System.out.println("分片总数: " total);
for (int i = 0; i < total; i ) {
File chunkFile = new File(chunkFolder i);
System.out.println("分片: " (i 1) ", chunkFile: " chunkFile.getName());
try (RandomAccessFile randomAccessFileWriter = new RandomAccessFile(chunkFile, "rw");
FileChannel fileChannelWriter = randomAccessFileWriter.getChannel()) {
int len;
buffer.clear();
while ((len=fileChannelReader.read(buffer)) != -1) {
//改为读模式
buffer.flip();
fileChannelWriter.write(buffer);
//改为写模式
buffer.compact();
//如果分片的大小>=分片的大小,读下一块
if (chunkFile.length() >= shareSize) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
//合并文件
mergeFile(new File(chunkFolder));
}
/**
* 合并块文件
* @param chunkFolder
*/
public static void mergeFile(File chunkFolder) throws IOException {
//块文件夹下文件列表
File[] files = chunkFolder.listFiles();
assert files != null;
List<File> fileList = Arrays.stream(files).sorted(
Comparator.comparing(o -> Long.valueOf(o.getName())))
.collect(Collectors.toList());
//合并的文件
File mergeFile = new File("D:\\IDM\\videos\\chunks\\java_merge.mp4");
//创建新文件
boolean success = mergeFile.createNewFile();
//创建写对象
RandomAccessFile randomAccessFileWriter = new RandomAccessFile(mergeFile, "rw");
byte[] bytes = new byte[1024];
for (int i = 0; i < fileList.size(); i ) {
File chunkFile = fileList.get(i);
logger.info("合并------>分片:{},chunkFile:{}", i 1, chunkFile.getName());
RandomAccessFile randomAccessFileReader = new RandomAccessFile(chunkFile, "r");
int len;
while ((len = randomAccessFileReader.read(bytes)) != -1) {
randomAccessFileWriter.write(bytes, 0, len);
}
randomAccessFileReader.close();
}
randomAccessFileWriter.close();
Arrays.stream(files).forEach( f->{
f.delete();
} );
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhfhcbch
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
怎样阻止微信小程序自动打开
PHP中文网 06-13