开发者社区 问答 正文

java文件copy 打开复制后的文件出错 求助!!!!!! 400 请求报错 

     问题在代码中提出,请大家指出一下问题所在

			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();

展开
收起
kun坤 2020-05-29 11:49:02 501 分享 版权
1 条回答
写回答
取消 提交回答
  • 建议直接用 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里面,然后遍历再写入文件 会出错,而不是怎么复制文件

    2020-05-29 11:49:11
    赞同 展开评论