This example shares the specific code for Java to implement the XOR operation of two files for your reference. The specific content is as follows
The following code is to generate a new file after two files of the same size. The specific idea is to use the FileInputStream method to read the file, perform XOR operation on the two files in bytes, and then use the FileOutputStream method to output the file. The specific code is as follows:
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class Test{ int i=0; static int count=0; public static void main(String[] args) throws IOException { //Create byte input stream FileInputStream filea = new FileInputStream("d://JavaXor//a"); FileInputStream fileb = new FileInputStream("d://JavaXor//b"); File outfile=new File("d://JavaXor//outfile"); int filesizea=filea.available();//Calculate the file size FileOutputStream fos=new FileOutputStream(outfile); byte[] bufa = new byte[1024]; //Storage byte array of filea file byte[] bufb = new byte[1024]; //Storage byte array of fileb file byte[] bufc = new byte[1024]; //Storage the byte array after two files XOR byte[] buf_yu=new byte[filesizea%1024]; //Storage the last part of the file XOR, because the size of the file may not be an integer multiple of 1024. If you continue to use bufc, the output file size will be larger than the value./ That is, the last byte array is not filled with 1024 bytes int hasReada = 0; int hasReadb = 0; //The read() method of the FileInputStream class puts the read stream in bufa and assigns the number of bytes to hasReada //The following function treats the last part of the file and other parts respectively while( ((hasReada=filea.read(bufa))>0) && ((hasReadb=fileb.read(bufb))>0) ) { if(count<filesizea-filesizea%1024) { for(int i=0;i<bufa.length && count<filesizea-filesizea%1024;i++) { bufc[i]=(byte)((bufa[i]^bufb[i]) & 0xFF); count++; } fos.write(bufc); } else if(count>=filesizea-filesizea%1024 && count<filesizea) { for(int j=0; count>=filesizea-filesizea%1024 && count<filesizea) { for(int j=0; count>=filesizea-filesizea%1024 && count<filesizea ;j++) { buf_yu[j]=(byte)((bufa[j]^bufb[j]) & 0xFF); count++; } fos.write(buf_yu); } } System.out.println(count); filea.close(); //Close the input and output stream fileb.close(); fos.close(); } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.