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
(待后续知识改进)
- Java基础05(补充二)-异或的应用
- Java基础补充
- JAVA基础补充点
- java基础补充
- java基础 细节补充
- java基础补充
- Java基础 集合补充
- Java基础--Android中泛型的应用(二)
- java基础巩固训练营【第一轮】((二)JAVA基础 补充
- CSS的应用补充
- 补充:this的应用
- Remoting 基础的补充
- 异或的应用
- Java学习-异或应用
- java基础-^ 异或运算
- JAVA基础-异或问题
- 传智播客 Java web基础补充
- Java基础01-其他补充
- 在一个字符串中删除另一个字符串中存在的字符
- ubuntu 10.10下搭建android开发环境 安装必要工作用软件
- 如何有效管理工时 - 2
- 第六周实验报告2
- C#学习:综合练习聊天机器人第一版
- Java基础05(补充二)-异或的应用
- hadoop的Streaming学习(续)
- jquery插件弹出对话框
- 用静态工厂方法代替构造函数
- Qt4.6 QMessageBox 使用大全
- jquery插件之面板
- 第六周任务三之平面坐标点
- 有时候经常会出现端口占用的情况。怎么查看端口占用情况?
- Android需不需要手动退出