程序具有加密和解密两大功能。
用户选定一个文件,加密生成一个新文件,新文件文件名在原文件名后加enc,扩展名不变。如果用户选定的是一个文件夹,则递归加密文件夹下文件及子文件夹下的所有文件。
用户选定一个文件,解密生成一个新文件,新文件文件名去掉文件名后面的enc,扩展名不变。如果用户选定的是一个文件夹,则递归解密文件夹下文件及子文件夹下的所有文件。
实现文件和文件夹压缩功能,压缩后的文件能用常见解压软件进行解压。
压缩时,用户选定一个文件,压缩生成一个新文件,新文件文件名在原文件名扩展名后加.zip,如果用户选定的是一个文件夹,则递归压缩文件夹下文件及子文件夹下的所有文件,压缩包文件名为目录名+.zip。
Main.java
package FileTest;
import java.io.*;
import java.util.Base64;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
class ZipUtil{
public static void ZipFile (File oldFile) throws IOException {
//被压缩的文件
FileInputStream fileInputStream = new FileInputStream(oldFile);
//输出的新压缩包
String path = oldFile.getAbsolutePath();
String newPath=path+".zip";
File newFile = new File(newPath);
//判断新压缩包是否已经存在
if(!newFile.exists()) {
//如果文件不存在就新建
System.out.println("压缩新文件不存在,新建");
newFile.createNewFile();
}else{
//如果文件存在,则删除后重新创建新的文件
System.out.println("压缩新文件存在,则删除后重新创建新的文件");
newFile.delete();
newFile.createNewFile();
}
//原文件的输出流
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
//原文件创建新的zip输出流
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
//创建新的压缩文件
ZipEntry zipEntry = new ZipEntry(oldFile.getName());
//向新压缩包中添加文件,重新流定位,开始写入新的文件
zipOutputStream.putNextEntry(zipEntry);
//把原文件的内容写入压缩包中的新文件
byte[] bytes = new byte[1024];
int length;
while((length=fileInputStream.read(bytes))!=-1){
zipOutputStream.write(bytes,0,length);
}
//关闭输出输入文件流
zipOutputStream.close();
fileOutputStream.close();
fileInputStream.close();
}
public static void ZipFolder(File ordFile,String ordFileName,ZipOutputStream zipOutputStream) throws IOException {
//当前压缩对象是文件夹
if(ordFile.isDirectory()){
//遍历当前文件夹的子文件
File[] listFiles = ordFile.listFiles();
// 空文件夹的处理
if(listFiles==null||listFiles.length<=0){
zipOutputStream.putNextEntry(new ZipEntry(ordFile.getName()+"/"));
//关闭当前zip条目读取下一条
zipOutputStream.closeEntry();
}
else {
for(File childFile:listFiles){
//递归,压缩对象变成子文件或子目录
// +"/"分级目录,保留原来的文件结构
ZipFolder(childFile,ordFileName+"/"+childFile.getName(),zipOutputStream);
}
}
}else{
//当前压缩对象不是文件夹,是文件
//创建文件输入流
FileInputStream fileInputStream = new FileInputStream(ordFile);
//创建新的压缩条目
ZipEntry zipEntry = new ZipEntry(ordFileName);
//向新压缩包中添加文件,重新流定位,开始写入新的条目
zipOutputStream.putNextEntry(zipEntry);
//把原文件的内容写入压缩包中的新文件
byte[] bytes = new byte[1024];
int length;
//子文件以字节码形式存储在新压缩包中
while((length=fileInputStream.read(bytes))!=-1){
zipOutputStream.write(bytes,0,length);
}
//关闭文件输入流,而zip输出流不关闭
fileInputStream.close();
}
}
static public void UnZipFile(File ordFile) throws IOException {
//被解压文件的绝对路径
String ordPath = ordFile.getAbsolutePath();
//压缩包的输入流
FileInputStream fileInputStream = new FileInputStream(ordFile);
ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
//获取压缩包中的条目文件
ZipEntry nextEntry = zipInputStream.getNextEntry();
//对每个压缩文件进行解密
byte[] bytes = new byte[1024];
while(nextEntry!=null){
//把文件后缀名.zip删除
String newPath = ordPath.replaceAll(".zip","");
//创建新文件
File newFile = new File(newPath, nextEntry.getName());
File newFileParent = newFile.getParentFile();
//判断新压缩包是否已经存在
if(!newFileParent.exists()) {
//如果文件不存在就新建
newFileParent.mkdirs();
}
if(newFile.exists()){
//如果文件存在,则删除后重新创建新的文件
newFile.delete();
}
newFile.createNewFile();
//新文件的输出流
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
int length;
//把zip文件内容输出到新文件中
while((length=zipInputStream.read(bytes))!=-1){
fileOutputStream.write(bytes,0,length);
}
//关闭当前新文件的输出流
fileOutputStream.close();
//获得压缩包下一个条目文件
nextEntry = zipInputStream.getNextEntry();
}
//关闭zip输入流
zipInputStream.closeEntry();
zipInputStream.close();
}
}
class Base64Util{
//加密
static public String EncodeBase64(String str){
byte[] bytes = str.getBytes();
String encode = Base64.getEncoder().encodeToString(bytes);
return encode;
}
//解密
static public String DecodeBase64(String str){
byte[] bytes = Base64.getDecoder().decode(str);
String s = new String(bytes);
return s;
}
}
class FileUtil{
static public void FileToZip(String path) throws IOException {
File file = new File(path);
if(file.isDirectory()) {
System.out.println("压缩"+path+":isDirectory");
//新压缩包名
String newPath=path+".zip";
//新压缩包
FileOutputStream fileOutputStream = new FileOutputStream(newPath);
ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
//对文件夹进行递归压缩
ZipUtil.ZipFolder(file,file.getName(),zipOutputStream);
//关闭输出流
zipOutputStream.close();
fileOutputStream.close();
}else{
System.out.println("压缩"+path+":isFile");
ZipUtil.ZipFile(file);
}
}
static public void ZipToFile(String path) throws IOException {
System.out.println("解压:"+path);
File file = new File(path);
ZipUtil.UnZipFile(file);
}
static private BufferedReader bufferedReader;
final static private boolean encode=true;
final static private boolean decode=false;
static private StringBuilder nowString=new StringBuilder("");
//文件加密
static public void EncodeFile(File file){
String fileToString = FileToString(file);
//加密
String s = Base64Util.EncodeBase64(fileToString);
//清空文件并重新写入
ReWriteInfoForFile(file,s);
System.out.println("文件"+file.getAbsolutePath()+"加密后:"+"\n"+s);
//添加文件名后缀名
ChangeSufFileName(file,true);
}
static public void DecodeFile(File file){
String fileToString = FileToString(file);
String s = Base64Util.DecodeBase64(fileToString);
//清空文件并重新写入
ReWriteInfoForFile(file,s);
System.out.println("文件"+file.getAbsolutePath()+"解密后:"+"\n"+s);
ChangeSufFileName(file,false);
}
//修改文件名后缀名
static public void ChangeSufFileName(File file,boolean isAdd){
//文件名后加enc
String fileName = file.getName();
if(isAdd){
fileName=fileName.substring(0, fileName.length()-4)+".enc"+fileName.substring(fileName.length()-4);
}
else {
fileName=fileName.replaceAll(".enc", "");
}
String fileParent = file.getParent();
//文件所在文件夹路径+新文件名
String newPathName=fileParent+'\\'+fileName;
file.renameTo(new File(newPathName)); //修改名后,原文件会被删除
System.out.println("修改后的文件名为"+newPathName);
//System.out.println("文件:"+file.getName()+":"+file.exists());
}
//文件转化成字符串
static public String FileToString(File file){
try {
FileInputStream fileInputStream = new FileInputStream(file);
StringBuilder stringBuilder=new StringBuilder();
int length;
byte[] buf = new byte[1024];
//返回一个整型字符数据
while((length=fileInputStream.read(buf))!=-1){
stringBuilder.append(new String(buf,0,length));
}
String fileTextString = stringBuilder.toString();
fileInputStream.close();
return fileTextString;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void ReWriteInfoForFile(File file,String str) {
try {
if(!file.exists()) {
file.createNewFile();
}
//清空文件
FileWriter fileWriter =new FileWriter(file);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
//重新写入
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] bytes = str.getBytes();
fileOutputStream.write(bytes);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//递归加密or解密
static public void RecursiveEncodeOrDecode(String Path,boolean isEncode){
File folder = new File(Path);
if(!folder.exists()){
System.out.println("文件"+Path+"不存在");
return ;
}
if(!folder.isDirectory()){
if(isEncode){
System.out.println("文件"+Path+"进行加密");
EncodeFile(folder);
} else {
System.out.println("文件"+Path+"进行解密");
DecodeFile(folder);
}
return ;
}
File[] listFiles = folder.listFiles();
if(null==listFiles||listFiles.length==0){
System.out.println("文件夹"+Path+"为空");
return ;
}
for(File file:listFiles) {
if (file.isDirectory()) {
System.out.println("文件夹" + file.getAbsolutePath() + "继续递归");
RecursiveEncodeOrDecode(file.getAbsolutePath(),isEncode);
} else {
if(isEncode){
System.out.println("文件"+file.getAbsolutePath()+"进行加密");
EncodeFile(file);
} else {
System.out.println("文件"+file.getAbsolutePath()+"进行解密");
DecodeFile(file);
}
}
}
}
}
public class Main {
// public static void main(String[] args) {
// String path="D:\\desktop\\Text\\123.txt";
// path="D:\\desktop\\Text\\123";
// //压缩
// FileUtil.FileToZip(path);
// path=path+".zip";
// //解压
// FileUtil.ZipToFile(path);
//文件/文件夹路径
// String Path="D:\\desktop\\Text";
// //加密
// FileUtil.RecursiveEncodeOrDecode(Path,true);
// String s = FileUtil.FileToString(new File(Path));
// System.out.println();
// //解密
// FileUtil.RecursiveEncodeOrDecode(Path,false);
// String str = FileUtil.FileToString(new File(Path));
// }
//
}
Test.java
package FileTest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import java.awt.Font;
import java.awt.Label;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import java.awt.Choice;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.awt.Color;
import javax.swing.JLabel;
import FileTest.Main;
public class Test {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
String fileName[]={""};
frame = new JFrame();
frame.getContentPane().setFont(new Font("宋体", Font.PLAIN, 20));
frame.setBounds(100, 100, 817, 463);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lab = new JLabel("\u6587\u4EF6\u540D\uFF1A");
lab.setFont(new Font("宋体", Font.PLAIN, 20));
lab.setBounds(81, 10, 591, 25);
frame.getContentPane().add(lab);
JTextArea textArea = new JTextArea();
textArea.setFont(new Font("Monospaced", Font.PLAIN, 13));
textArea.setForeground(Color.BLACK);
textArea.setEditable(false);
textArea.setBounds(81, 39, 589, 272);
frame.getContentPane().add(textArea);
JButton btn2 = new JButton("\u538B\u7F29");
btn2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
FileUtil.FileToZip(fileName[0]);
textArea.setText(fileName[0]+"压缩成功!");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btn2.setFont(new Font("宋体", Font.PLAIN, 20));
btn2.setBounds(334, 321, 99, 33);
frame.getContentPane().add(btn2);
JButton btn22 = new JButton("\u89E3\u538B");
btn22.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
FileUtil.ZipToFile(fileName[0]);
textArea.setText(fileName[0]+"解压成功!");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btn22.setFont(new Font("宋体", Font.PLAIN, 20));
btn22.setBounds(334, 364, 99, 33);
frame.getContentPane().add(btn22);
JButton btn3 = new JButton("\u52A0\u5BC6");
btn3.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
long startTime = System.currentTimeMillis();
//do something
try {
FileUtil.RecursiveEncodeOrDecode(fileName[0],true);
textArea.setText(fileName[0]+"加密成功!");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间:" + (endTime - startTime) + "ms");
}
});
btn3.setFont(new Font("宋体", Font.PLAIN, 20));
btn3.setBounds(575, 321, 99, 33);
frame.getContentPane().add(btn3);
JButton btn33 = new JButton("\u89E3\u5BC6");
btn33.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
long startTime = System.currentTimeMillis();
//do something
try {
FileUtil.RecursiveEncodeOrDecode(fileName[0],false);
textArea.setText(fileName[0]+"解密成功!");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间:" + (endTime - startTime) + "ms");
}
});
btn33.setFont(new Font("宋体", Font.PLAIN, 20));
btn33.setBounds(575, 364, 99, 33);
frame.getContentPane().add(btn33);
JButton btn1 = new JButton("\u6253\u5F00\u6587\u4EF6");
btn1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JFileChooser jfc =new JFileChooser("D:\\desktop\\Text");
jfc.showDialog(btn1, null);
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.showOpenDialog(null);
File file=jfc.getSelectedFile();
fileName[0] = file.getAbsolutePath();
lab.setText(fileName[0]);
System.out.println(fileName[0]);
//原文件的输出流
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
StringBuilder textContent=new StringBuilder();
int length;
try {
while((length=fileInputStream.read())!=-1){
textContent.append((char)(length));
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
textArea.setText(textContent.toString());
}
});
btn1.setFont(new Font("宋体", Font.PLAIN, 20));
btn1.setBounds(81, 321, 149, 33);
frame.getContentPane().add(btn1);
JButton btn11 = new JButton("\u6253\u5F00\u6587\u4EF6\u5939");
btn11.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JFileChooser jfc =new JFileChooser("D:\\desktop\\Text");
jfc.showDialog(btn1, null);
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.showOpenDialog(null);
File file=jfc.getSelectedFile();
fileName[0] = file.getAbsolutePath();
lab.setText(fileName[0]);
System.out.println(fileName[0]);
textArea.setText("文件夹:"+fileName[0]);
}
});
btn11.setFont(new Font("宋体", Font.PLAIN, 20));
btn11.setBounds(81, 364, 149, 33);
frame.getContentPane().add(btn11);
}
}