本文實例為大家分享了java實現兩個文件的異或運算的具體代碼,供大家參考,具體內容如下
以下代碼是將兩個大小相同的文件異或之后生成一個新的文件,具體思想是用fileinputstream方法讀取文件,以字節(jié)為單位對兩個文件進行異或運算,然后用fileoutputstream方法輸出文件,具體代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
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 { //創(chuàng)建字節(jié)輸入流 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(); //計算文件的大小 fileoutputstream fos= new fileoutputstream(outfile); byte [] bufa = new byte [ 1024 ]; //存放filea文件的字節(jié)數組 byte [] bufb = new byte [ 1024 ]; //存放fileb文件的字節(jié)數組 byte [] bufc = new byte [ 1024 ]; //存放兩個文件異或后的字節(jié)數組 byte [] buf_yu= new byte [filesizea% 1024 ]; //存放文件異或的最后一部分,因為文件的大小可能不是1024的整數倍,如果繼續(xù)用bufc的話輸出的文件大小會比應有值大 //就是最后一個字節(jié)數組沒有放滿1024個字節(jié) int hasreada = 0 ; int hasreadb = 0 ; //fileinputstream類的read()方法把讀取的流放在bufa中,并且返回字節(jié)的個數賦給hasreada //下面的函數就是將文件的最后一部分與其他部分分別對待 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 ;j++) { buf_yu[j]=( byte )((bufa[j]^bufb[j]) & 0xff ); count++; } fos.write(buf_yu); } } system.out.println(count); filea.close(); //關閉輸入輸出流 fileb.close(); fos.close(); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/u013555975/article/details/50205719