问题在代码中提出,请大家指出一下问题所在
FileInputStream fis = new FileInputStream("h:/test.pdf"); FileOutputStream fos = new FileOutputStream("h:/temp.pdf"); byte[] buffer = new byte[1024*8]; List<byte[]> list = new ArrayList<byte[]>(); int count=0; while(count!=-1){ count = fis.read(buffer); if(count==buffer.length){ list.add(buffer); /** * 如果把write写在这里文件复制得到的文件 * 用pdf reader打开不会出错 * */ //fos.write(buffer); } else if(count<buffer.length&&count>0){ byte[] temp = new byte[count]; System.arraycopy(buffer, 0, temp,0, temp.length); list.add(temp); //fos.write(temp); } } /** * 但是如果先把所又读取 的数据保存在List里面 * 再遍历写入文件 * 用pdfreader打开文件报错 * * */ for(int i=0;i<list.size();i++){ fos.write(list.get(i)); } fos.close();
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
建议直接用 commons-io 项目中的 FileUtils.copyFile(...),别再自己造轮子######肯定是有原因才这样问的,而且我真的想知道 这两种方式为什么会不一样,一个正确一个错误,你能说说么?######
public static void copyByChannel(String src, String dest) throws Exception { RandomAccessFile raf = new RandomAccessFile(src, "r"); FileOutputStream fos = new FileOutputStream(dest); try {
FileChannel srcChannel = raf.getChannel();
FileChannel destChannel = fos.getChannel();
destChannel.transferFrom(srcChannel, 0, srcChannel.size());
} finally {
raf.close();
fos.close();
}
}
public static void copy(String src, String dest) throws Exception {
final int SIZE = 2048 * 80;
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fis = new FileInputStream(src);
bis = new BufferedInputStream(fis);
fos = new FileOutputStream(dest);
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[SIZE];
int length = -1;
while((length = bis.read(buffer, 0, SIZE)) != -1) {
bos.write(buffer, 0, length);
bos.flush();
}
} finally {
bis.close();
fis.close();
bos.close();
fos.close();
}
}</pre>
######额 这些我知道 我关心的是为什么先把buffer保存在List里面,然后遍历再写入文件 会出错,而不是怎么复制文件