论坛首页 Java企业应用论坛

IO进阶 用InputStream和OutPutStream实现凯撒密码

浏览 2621 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-03-21  
package chap16;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

public class CodeTester {

	/**
	 * @param args
	 */
	public static void main(String[] args)  throws Exception
	{
		  Scanner cin = new Scanner(System.in);
		  System.out.println("input the url of input file");
		  //输入inptufile的路径
		  String inputfile = cin.next();
		  System.out.println("input the url of the outfile");
		  String outputfile = cin.next();
		  
		  Code myCode = new Code(3);
		  myCode.enFile(inputfile, outputfile);
	}
}




class Code {
	public Code(int akey) {
		this.key = akey;
	}

	/*
	 * 输入输出文件交互 @param infile 输入文件路径 @param outfile 输出文件路径
	 * 
	 */

	public void enFile(String infile, String outfile) throws Exception {
		InputStream in = null;
		OutputStream out = null;

		try {
			in = new FileInputStream(infile);
			out = new FileOutputStream(outfile);

			changeCode(in, out);

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (in == null)
				in.close();
			if (out == null)
				out.close();
		}
	}

	/*
	 * 字符转换 @param FileInputStream 输入流 @param FileOutputStream 输出流
	 */
	public void changeCode(InputStream in, OutputStream out) {

		boolean done = false;

		while (!done) {
			try {
				int next = in.read();
				if(next == -1) done = true;
				else
				{
					// in.read()输出的是一些整型的值,强制转换成byte类型
					byte temp = (byte) next;
					// 进行加密
					byte c = this.jiami(temp);
					out.write(c);
				}
				

			} catch (IOException ex) {
				ex.printStackTrace();
			}

		}

	}

	/*
	 * 对字符加密 @param byte b 待加密的字符 @return code 加密后的字符
	 */
	public byte jiami(byte b) {
		byte temp = (byte) (b + this.key);
		return temp;
	}

	// 钥匙
	private int key;
}




运行结果:
input the url of input file
O:\\myproject\\J2SE项目\\Test\\src\\bejiami.txt
input the url of the outfile
O:\\myproject\\J2SE项目\\Test\\src\\afjiami.txt
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics