Java基础05(补充二)-异或的应用

来源:互联网 发布:阿里巴巴比淘宝 编辑:程序博客网 时间:2024/06/08 04:21

1.异或的性质:

    一个数,异或其他的数两次后,还是其本身!

 

2.应用:简单的文件加密程序

   代码:

import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.File;import java.io.IOException;import java.io.FileNotFoundException;class Encrypt {private static final int PASSWORD = 0x12345678;private static final String SUFFIX = ".enc";public void doEncrypt(String path) {FileInputStream fis = null;FileOutputStream fos = null;try {File file = new File(path);File newFile = new File(path+SUFFIX);fis = new FileInputStream(file); //FileNotFoundExceptionfos = new FileOutputStream(newFile); //FileNotFoundExceptionbyte [] buf = new byte[1024];int len = 0;while((len=fis.read(buf))!=-1) { //IOExceptionfor(int i = 0;i<len;i++){buf[i]=(byte)(buf[i]^PASSWORD); }fos.write(buf,0,len); //IOException}}catch(FileNotFoundException e) {throw new RuntimeException("文件不存在,请重试!");}catch(IOException e) {throw new RuntimeException("文件读取异常!");}finally {try {if(fis!=null)fis.close();}catch(Exception e ) {throw new RuntimeException("文件读取流异常!");}try {if(fos!=null)fos.close();}catch(Exception e) {throw new RuntimeException("文件存储流异常!");}}}public void doDecrypt(String path) {int index = path.lastIndexOf(SUFFIX);if(index!=(path.length()-SUFFIX.length())) {System.out.println("文件类型不正确!请重试!");return;}FileInputStream fis = null;FileOutputStream fos = null;try {File file = new File(path);File newFile = new File(path.substring(0,index));fis = new FileInputStream(file); //FileNotFoundExceptionfos = new FileOutputStream(newFile); //FileNotFoundExceptionbyte [] buf = new byte[1024];int len = 0;while((len=fis.read(buf))!=-1) { //IOExceptionfor(int i = 0;i<len;i++){buf[i]=(byte)(buf[i]^PASSWORD); }fos.write(buf,0,len); //IOException}}catch(FileNotFoundException e) {throw new RuntimeException("文件不存在,请重试!");}catch(IOException e) {throw new RuntimeException("文件读取异常!");}finally {try {if(fis!=null)fis.close();}catch(Exception e ) {throw new RuntimeException("文件读取流异常!");}try {if(fos!=null)fos.close();}catch(Exception e) {throw new RuntimeException("文件存储流异常!");}}}public static void main(String [] args) {Encrypt e = new Encrypt();if(args.length != 2) {System.out.println("参数输入错误!请重新输入!");return;}if(args[0].equalsIgnoreCase("encrypt"))e.doEncrypt(args[1]);else if(args[0].toUpperCase().equals("DECRYPT")) {e.doDecrypt(args[1]);}}}


测试方法:

javac Encrypt.java

java Encrypt d:\1.txt encrypt

 

(待后续知识改进)

原创粉丝点击