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

我在做一个基于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()却能显示出正确的大小,请问为什么会出现这种情况?

阅读 2.7k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题