判断PDF文件是否相同(通过二进制流判断)

一、Java代码  

1、将PDF转为字节流
    /*
     * @step
     *  1.使用BufferedInputStream和FileInputStream从File指定的文件中读取内容;
     *  2.然后建立写入到ByteArrayOutputStream底层输出流对象的缓冲输出流BufferedOutputStream
     *  3.底层输出流转换成字节数组,
     */
    public static byte[] getPDFBinary(String fileName)
    {
        //字节输入流      
        FileInputStream fin = null;
        //字节输入缓冲流:先从磁盘中将要读取的内容放入到内存中,再一次性从内存中取出来,避免了读一段取一段
        BufferedInputStream bin = null;
        //字节输出缓冲流:先将要输出的内容放入到内存中,再一次性全都输出。
        BufferedOutputStream bout = null;
        //字节数组输出流,将字节数据写入到字节数组中
        ByteArrayOutputStream baos = null;
        
        try
        {
            //建立读取文件的文件输出流
            fin = new FileInputStream(fileName);
            //在文件流上安装节点流(更大效率读取)
            bin = new BufferedInputStream(fin);
            //创建一个新的byte数组输出流,它具有指定大小的缓冲区容量
            baos = new ByteArrayOutputStream();
            //创建一个新的缓冲输出流,将以数据写入指定的底层出入流
            bout = new BufferedOutputStream(baos);
            byte[]  buffer = new byte[2048];
            int len = bin.read(buffer);
            while(len != -1)
            {
                //void write(byte[] b, int off, int len)
                //将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流
                bout.write(buffer,0,len);
                len = bin.read(buffer);
            }
            //刷新此输出流,并强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            return bytes;            
        }
        catch(FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }finally {
        try{
            fin.close();
            bin.close();
            //关闭 ByteArrayOutputStream 无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何 IOException
            //baos.close();
            bout.close();        
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

    }
        return null;
  }

2、比较两个数组是否相同(两个PDF文件转为字节数组)

Arrays.equals(bytesA,bytesE);

二、C#

1、将PDF转为字节流

        public static byte[] GetBinary(String filePath)
        {
            //读取文件
            FileStream stream = new FileInfo(filePath).OpenRead();
            byte[] buffer = new byte[stream.Length];
            //从流中读取字节块并将该数据写入给定缓冲区中
            stream.Read(buffer,0,Convert.ToInt32(stream.Length));
            stream.Close();
            return buffer;          
        }

2、比较两个数组是否相同(两个PDF文件转为字节数组)

Enumerable.SequenceEqual(byte1,byte2);

参考:https://blog.csdn.net/congcongsuiyue/article/details/39964119

猜你喜欢

转载自www.cnblogs.com/wennyjane/p/10277846.html