本文实例为大家分享了java实现两个文件的异或运算的具体代码,供大家参考,具体内容如下
以下代码是将两个大小相同的文件异或之后生成一个新的文件,具体思想是用fileinputstream方法读取文件,以字节为单位对两个文件进行异或运算,然后用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
{
//创建字节输入流
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文件的字节数组
byte [] bufb = new byte [ 1024 ]; //存放fileb文件的字节数组
byte [] bufc = new byte [ 1024 ]; //存放两个文件异或后的字节数组
byte [] buf_yu= new byte [filesizea% 1024 ]; //存放文件异或的最后一部分,因为文件的大小可能不是1024的整数倍,如果继续用bufc的话输出的文件大小会比应有值大
//就是最后一个字节数组没有放满1024个字节
int hasreada = 0 ;
int hasreadb = 0 ;
//fileinputstream类的read()方法把读取的流放在bufa中,并且返回字节的个数赋给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