今天CSDN的博客编辑器更新了。。。
程序一共三个方法:
main方法、加密方法、解密方法
首先设置要加密的原文件:我的是G:\my.png文件,也可以设置其他文件。加密文件和解密文件是生成的,不用设置,只添加个路径就可以了。
要加密的话运行解密方法:EnFile(file1,file2);
要解密的话运行解密方法:EnFile(file2,file3);
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();
}
}
}
}