JavaNIO处理文件合并时候碰到的一个问题

发布于 2022-09-04 21:09:33 字数 1304 浏览 21 评论 0

我在做一个基于webuploader和spring的文件分片上传的Demo,以下的代码是处理文件的核心部分。

if(parseInt(req.getParameter("chunk"))==0){
    try {
        file.transferTo(targetFile);
        System.out.println(targetFile.length());
    }catch (Exception e) {
        e.printStackTrace();
        return "fail";
    }
    //filesList.add(new File(path+pos+req.getParameter("chunk")));
}else{
    file.transferTo(new File(path+pos+req.getParameter("chunk")));
    filesList.add(new File(path+pos+req.getParameter("chunk")));
}

System.out.println(filesList.size());

if((filesList.size()+1)==(parseInt(req.getParameter("chunks")))){
    FileChannel mFileChannel = new FileOutputStream(targetFile).getChannel();
    try {
        for (File fin : filesList) {
            FileChannel inFileChannel = new FileInputStream(fin).getChannel();

            //src,position(start),size

            mFileChannel.transferFrom(inFileChannel, mFileChannel.size(), inFileChannel.size());

            inFileChannel.close();
        }
    }catch (Exception e) {
        e.printStackTrace();
        return "fail";
    }
    mFileChannel.close();
    filesList.clear();
    return "success";
}
return "success";
}

我遇到的问题是,在对mFileChannel进行初始化的时候,发现mFileChannel.size()总等于0,而在之前打印targetFile.size()却能显示出正确的大小,请问为什么会出现这种情况?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文