Java IO--实现文件的加密解密

今天CSDN的博客编辑器更新了。。。


package demo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

public class FileEncrytionTest
{
	public static void main(String[] args)
	{
		//源文件
		File file1 = new File("g:"+File.separator+"my.png");
		//加密文件
		File file2 = new File("g:"+File.separator+"myenc.png");
		//解密文件
		File file3 = new File("g:"+File.separator+"mydec.png");
//		EnFile(file1,file2);
		DecFile(file2,file3);
		
	}

	//加密方法
	public static void EnFile(File srcFile,File tarFile)
	{
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null ;
		//源文件
		File file1 = srcFile;
		//加密文件
		File file2 = tarFile;
		try
		{
			InputStream is = new FileInputStream(file1);
			OutputStream os = new FileOutputStream(file2);
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(os);
			
			byte[] data = new byte[100];
			int len = 0 ;
			while((len = bis.read(data, 10, 60))!= -1)
			{
				if(len == 60) 
				{
					bos.write(data,0,100);
				}else {
					bos.write(data,10,len);
				}
				System.out.println(Arrays.toString(data));
			}
			
		} catch ( Exception e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				if(bis != null)
				{
					/* 关闭管子 */
					bis.close();
					bis = null ; 
				}
			}catch(IOException e)
			{
				e.printStackTrace();
			}
			
			try
			{
				if(bos != null)
				{
					/* 关闭管子 */
					bos.close();
					bos = null ; 
				}
			}catch(IOException e)
			{
				e.printStackTrace();
			}
		}
	}
	//解密方法
	public static void DecFile(File srcFile,File tarFile)
	{
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null ;
		//源加密文件
		File file1 = srcFile;
		//解密文件
		File file2 = tarFile;
		try
		{
			InputStream is = new FileInputStream(file1);
			OutputStream os = new FileOutputStream(file2);
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(os);
			
			byte[] data = new byte[100];
			int len = 0 ;
			while((len = bis.read(data))!= -1)
			{
				if(len==100)
				{
					bos.write(data, 10, 60);
				}else
				{
					bos.write(data,0,len);
				}
				System.out.println(Arrays.toString(data));
			}
			
		} catch ( Exception e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				if(bis != null)
				{
					/* 关闭管子 */
					bis.close();
					bis = null ; 
				}
			}catch(IOException e)
			{
				e.printStackTrace();
			}
			
			try
			{
				if(bos != null)
				{
					/* 关闭管子 */
					bos.close();
					bos = null ; 
				}
			}catch(IOException e)
			{
				e.printStackTrace();
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_32965187/article/details/81067604