目前已经实现了的功能:
- 实现文件夹创建、删除,能够设置当前文件夹;
- 实现当前文件夹下的内容罗列;可以过滤特定类型的文件,根据文件名,文件大小,文件类型。
- 实现文件拷贝和文件夹拷贝(深度拷贝);能计算拷贝时间,能显示拷贝进度。
- 可以对指定文件进行加密和解密;
- 对指定文件进行压缩和解压
说明:
- Main.java里面封装了主程序类,基本的Swing组件类,改变当前目录的功能,各种监听事件的基类,各种文件操作的基类。
- 其他各类分别实现了对应的功能类以及事件监听类
代码:
- 主类
package FileManager;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
class UsualButton extends JButton {
private static final long serialVersionUID = 580568926541151945L;
//设置按钮名字与组件的首选大小
UsualButton(String name, int x, int y) {
super(name);
setPreferredSize(new Dimension(x, y));
}
UsualButton(String name) {
super(name);
setPreferredSize(new Dimension(100, 30));
}
}
class UsualFrame extends JFrame {
private static final long serialVersionUID = 2370368909446103217L;
//设置顶层窗口的名字,位置和大小
UsualFrame(String name, int x, int y, int w, int h) {
super(name);
setVisible(true);
setLocation(x, y);
setSize(w, h);
setLayout(new FlowLayout());
}
}
class MenuButton extends JButton {
private static final long serialVersionUID = -2775082217826075140L;
MenuButton(String name, ActionListener action) {
super(name);
setPreferredSize(new Dimension(100, 30));
addActionListener(action);
}
}
class ChangeAction extends Action {
private static String name = "改变目录";
private static String lname1 = "请输入地址";
private static int count = 1;
private static String m1 = "改变成功";
private static String m2 = "改变失败";
public void addAction() {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String s1 = jText1.getText();
if(Main.setCurrentFile(s1))
JOptionPane.showMessageDialog(frame, m1);
else
JOptionPane.showMessageDialog(frame, m2);
}
} );
}
ChangeAction() {
super(name, lname1, null, count);
}
}
class FileOperate {
//源文件名与目标文件名
protected String src, des;
//源文件与目标文件
protected File from, to;
//进行操作,返回该操作是否成功
public boolean operate() throws IOException {
return true;
}
//初始化当前文件名
FileOperate(String s) {
src = s;
}
//初始化源文件名与目标文件名
FileOperate(String s1, String s2) {
src = s1; des = s2;
}
//初始化当前文件
FileOperate(File f) {
from = f;
}
//初始化源文件与目标文件
FileOperate(File f, File t) {
from = f; to = t;
}
}
class Action implements ActionListener {
private String name; //名字
private String labelName1; //第一个标签的名字
private String labelName2; //第二个标签的名字
private int textCount; //文本输入框的数量
protected JButton button; //确认按钮
protected JFrame frame; //顶层窗口
protected JTextField jText1 = null, //最多可拥有两个输入框
jText2 = null;
Action() {}
//初始化框架的名字,标签名,文本框数量
Action(String name, String lname1, String lname2, int count) {
this.name = name;
labelName1 = lname1;
labelName2 = lname2;
textCount = count;
}
//为按钮添加事件
public void addAction() {}
//该功能对应的按钮的响应事件
@Override
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
int count = textCount;
// TODO Auto-generated method stub
//初始化顶层窗口
frame = new UsualFrame(name, 400, 400, 360, 160);
//初始化标签1
JLabel jLabel1 = new JLabel(labelName1);
frame.add(jLabel1);
//如果需要文本框1
if(--count >= 0) {
jText1 = new JTextField(30);
frame.add(jText1);
}
//初始化标签2
JLabel jLabel2 = new JLabel(labelName2);
frame.add(jLabel2);
//如果需要文本框2
if(--count >= 0) {
jText2 = new JTextField(30);
frame.add(jText2);
}
//确认按钮
button = new UsualButton("确认", 100, 30);
frame.add(button);
//为按钮添加响应事件,利用了类的多态性质
addAction();
}
});
}
}
public class Main {
static private JFrame menuFrame; //主面板
private static File current; //当前路径
//得到当前路径
public static File getCurrentFile() {
return current;
}
//改变当前路径
public static boolean setCurrentFile(String s) {
File temp = current;
current = new File(s);
if(current.exists()) return true;
else {
current = temp;
return false;
}
}
public static void main(String[] args) throws IOException {
current = new File((new File("")).getAbsolutePath());
//使用事件调度线程进行管理
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
menuFrame = new UsualFrame("主菜单", 200, 200, 800, 200);
//添加各种按钮
menuFrame.add(new MenuButton("创建文件夹", new CreateAction()));
menuFrame.add(new MenuButton("删除文件夹", new DeleteAction()));
menuFrame.add(new MenuButton("列举文件", new ListAction()));
menuFrame.add(new MenuButton("复制文件夹", new CopyAction()));
menuFrame.add(new MenuButton("文件加密/解密", new CodeAction()));
menuFrame.add(new MenuButton("文件压缩/解压", new ZipAction()));
menuFrame.add(new MenuButton("设置目录", new ChangeAction()));
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuFrame.setVisible(true);
}
});
}
}
- 创建文件类:
package FileManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;
public class CreateFile extends FileOperate{
//文件夹名,文件名
CreateFile(String pname, String fname) {
super(pname, fname);
}
//创建文件
public boolean operate() throws IOException {
//创建文件夹
File file = new File(src);
//如果成功创建文件夹
if(file.mkdirs()) {
System.out.println("文件夹创建成功!");
}
//创建文件
file = new File(src + "//" + des);
//如果成功创建文件
if(file.createNewFile()) {
System.out.println("文件创建成功!");
return true;
}
//如果某一项没有创建成功
return false;
}
//测试
public static void main(String[] args) throws IOException {
String s1 = "F:\\newfile\\newfile1\\newFile2";
String s2 = "1.txt";
CreateFile cf = new CreateFile(s1, s2);
cf.operate();
}
}
class CreateAction extends Action {
private static String name = "创建文件"; //顶层窗口名
private static String lname1 = "请输入地址"; //第一个标签的内容
private static String lname2 = "请输入文件名"; //第二个标签的内容
private static int count = 2; //两个输入框
private static String m1 = "创建成功"; //成功消息
private static String m2 = "创建失败"; //失败消息
public void addAction() {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//获取输入框内容
String s1 = jText1.getText(), s2 = jText2.getText();
try {
//若成功创建则弹出提示成功窗口
if(new CreateFile(s1, s2).operate())
JOptionPane.showMessageDialog(frame, m1);
//否则弹出提示失败的窗口
else
JOptionPane.showMessageDialog(frame, m2);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} );
}
//调用基类构造函数
CreateAction() {
super(name, lname1, lname2, count);
}
}
删除文件类:
package FileManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JOptionPane;
public class DeleteFile extends FileOperate {
DeleteFile(String name) {
super(new File(name));
}
public boolean operate() {
return deleteFile(from);
}
public boolean deleteFile(File path) {
if(path == null) return false;
if(path.exists()) {
File[] files = path.listFiles();
int n = files.length;
for(int i = 0; i < n; ++i) {
if(files[i].isFile())
files[i].delete();
else
deleteFile(files[i]);
}
path.delete();
}
else {
System.out.println("不存在该文件夹!");
return false;
}
return true;
}
public static void main(String[] args) {
String s = new String("F:\\newfile");
DeleteFile df = new DeleteFile(s);
df.operate();
}
}
class DeleteAction extends Action {
private static String name = "删除文件";
private static String lname1 = "请输入地址";
private static int count = 1;
private static String m1 = "删除成功";
private static String m2 = "删除失败";
public void addAction() {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String s1 = jText1.getText();
if(new DeleteFile(s1).operate())
JOptionPane.showMessageDialog(frame, m1);
else
JOptionPane.showMessageDialog(frame, m2);
}
} );
}
DeleteAction() {
super(name, lname1, null, count);
}
}
- 文件列举类:
package FileManager;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class FileList extends FileOperate {
FileFilter filter; //文件过滤器
//flag为false是不接受这些名字,flag为true是接受这些名字
public void setFileNameFilter(String[] names, boolean flag) {
filter = new FileFilter() {
@Override
public boolean accept(File pathname) {
if(pathname.isDirectory()) //文件夹不被检查
return true;
if(flag) {
//只要文件名里面包含这些可接受名字数组
//的任意一个即为true
for(String s : names) {
if(pathname.getName().contains(s)) {
return true;
}
}
return false;
}
else {
//只要文件名里面包含这些不可接受名字数组
//的任意一个即为false
for(String s : names) {
if(pathname.getName().contains(s)) {
return false;
}
}
return true;
}
}
};
}
//flag为false是不接受这些类型,flag为true是接受这些类型
public void setFileTypeFilter(String[] names, boolean flag) {
filter = new FileFilter() {
@Override
public boolean accept(File pathname) {
if(pathname.isDirectory()) //文件夹直接被接受
return true;
if(flag) {
//只要文件类型为这些可接受文件类型数组
//的任意一个即为true
for(String s : names) {
if(pathname.getName().endsWith(s)) {
return true;
}
}
return false;
}
else {
//只要文件类型为这些不可接受文件类型数组
//的任意一个即为false
for(String s : names) {
if(pathname.getName().endsWith(s)) {
return false;
}
}
return true;
}
}
};
}
//flag为false是小于该size被接受,flag为true是大于等于于该size被接受
public void setFileSizeFilter(long size, boolean flag) {
filter = new FileFilter() {
@Override
public boolean accept(File pathname) {
if(flag) {
if(pathname.length() >= size) {
return true;
}
else {
return false;
}
}
else {
if(pathname.length() < size) {
return true;
}
else {
return false;
}
}
}
};
}
//列举所有文件
public void listAll() {
listAll(from, 0);
}
//列举所有文件的递归程序,dir是当前文件(夹),num是层次
public void listAll(File dir, int num) {
if(dir == null) return;
if(dir.exists() == false)
return;
for(int i = 0; i < num; ++i) //显示当前文件的层次
System.out.printf("|--");
System.out.println("文件夹:" + dir.getName());
File[] files = dir.listFiles(filter); //进行文件筛选
for(File f : files) {
if(f.isDirectory()) { //如果是文件夹继续递归
listAll(f, num + 1);
}
else { //是文件直接输出名字
for(int i = 0; i <= num; ++i)
System.out.printf("|--");
System.out.println("文件:" + f.getName());
}
}
}
//初始化基类与文件过滤器
FileList() {
super(Main.getCurrentFile());
filter = null;
}
//测试
public static void main(String[] args) {
FileList fl = new FileList();
String[] names = {"C", "D"};
String[] types = {".java"};
long size = 4096;
fl.listAll();
System.out.println("----------------------------");
fl.setFileNameFilter(names, false);
fl.listAll();
System.out.println("----------------------------");
fl.setFileNameFilter(names, true);
fl.listAll();
System.out.println("----------------------------");
fl.setFileTypeFilter(types, false);
fl.listAll();
System.out.println("----------------------------");
fl.setFileTypeFilter(types, true);
fl.listAll();
System.out.println("----------------------------");
fl.setFileSizeFilter(size, false);
fl.listAll();
System.out.println("----------------------------");
fl.setFileSizeFilter(size, true);
fl.listAll();
}
}
class ListAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new UsualFrame("文件列举", 400, 400, 360, 300);
JPanel jPanel[] = new JPanel[3]; //创建3个面板
for(int i = 0; i < 3; ++i)
jPanel[i] = new JPanel();
JRadioButton single1[] = { //3个单选按钮,选择筛选的条件
new JRadioButton("文件大小"),
new JRadioButton("文件类型"),
new JRadioButton("文件名字")
};
JRadioButton single2[] = { //2个单选按钮,选择进行关键词保留还是过滤
new JRadioButton("关键词保留"),
new JRadioButton("关键词过滤")
};
ButtonGroup group1 = new ButtonGroup(); //两个按钮组分别存放两组单选按钮
ButtonGroup group2 = new ButtonGroup();
for(int i = 0; i < 3; ++i)
group1.add(single1[i]);
for(int i = 0; i < 2; ++i)
group2.add(single2[i]);
JLabel jLabel1 = new JLabel("筛选条件"); //标签的创建
jPanel[0].add(jLabel1);
for(int i = 0; i < 3; ++i)
jPanel[0].add(single1[i]);
JLabel jLabel2 = new JLabel("筛选或者保留");
jPanel[1].add(jLabel2);
for(int i = 0; i < 2; ++i)
jPanel[1].add(single2[i]);
for(int i = 0; i < 2; ++i)
frame.add(jPanel[i]);
JLabel jLabel3 = new JLabel("给出筛选值(以空格分隔)"); //输入关键词
frame.add(jLabel3);
JTextField text = new JTextField(20);
frame.add(text);
JButton button = new UsualButton("确认", 100, 30); //确认按钮
frame.add(button);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FileList fileList = new FileList();
boolean flag = false;
String[] args = text.getText().split(" ");
//判断是保留还是筛选
for(Component c : jPanel[1].getComponents()) {
if(c instanceof JRadioButton) {
if(((JRadioButton)c).isSelected()) {
String s = ((JRadioButton)c).getText();
if(s.equals("关键词保留"))
flag = true;
else if(s.equals("关键词筛选"))
flag = false;
break;
}
}
}
//判断选择的是什么功能
for(Component c : jPanel[0].getComponents()) {
if(c instanceof JRadioButton) {
if(((JRadioButton)c).isSelected()) {
String s = ((JRadioButton)c).getText();
if(s.equals("文件名字")) {
fileList.setFileNameFilter(args, flag);
}
else if(s.equals("文件类型")) {
fileList.setFileTypeFilter(args, flag);
}
else {
fileList.setFileSizeFilter(Integer.valueOf(args[0]), flag);
}
break;
}
}
}
fileList.listAll();
}
} );
}
});
}
}
- 文件加密/解密类:
package FileManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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 javax.swing.JOptionPane;
/**
* 文件加密/解密类
* 加密和解密的操作为与给定密钥进行异或运算
* 由异或运算的可逆性,可知该算法正确
* */
public class FileEncAndDec extends FileOperate {
//文件加密/解密的密钥
private static final int KEY = 0x79;
FileEncAndDec(String from, String to) throws IOException {
super(new File(from), new File(to));
}
//加密与解密是同一种操作方式,故统一成一个方法
public boolean operate() throws IOException {
if(!from.exists()) {
System.out.println("不存在该文件!");
return false;
}
if(!to.exists()) {
System.out.printf("重新创建文件");
if(to.createNewFile()) {
System.out.println("成功");
}
else {
System.out.println("失败");
}
}
InputStream in = new FileInputStream(from);
OutputStream out = new FileOutputStream(to);
//从源文件中读取数据与给定密钥进行异或运算,将结果存入目标文件
int data = -1;
while((data = in.read()) != -1) {
out.write(data ^ KEY);
}
in.close();
out.flush();
out.close();
return true;
}
//测试
public static void main(String[] args) throws IOException {
@SuppressWarnings("unused")
FileEncAndDec f = new FileEncAndDec("F://zzz//aaa.bmp", "F://zzz//bbb.bmp");
}
}
class CodeAction extends Action {
//基本属性
private static String name = "文件加密/解密";
private static String lname1 = "请输入源文件地址";
private static String lname2 = "请输入目标文件地址";
private static int count = 2;
private static String m1 = "加密/解密成功";
private static String m2 = "加密/解密失败";
//加入监听事件
public void addAction() {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//获取输入框信息
String s1 = jText1.getText(), s2 = jText2.getText();
try { //进行文件加密/解密操作
if(new FileEncAndDec(s1, s2).operate())
JOptionPane.showMessageDialog(frame, m1);
else
JOptionPane.showMessageDialog(frame, m2);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} );
}
//初始化基类
CodeAction() {
super(name, lname1, lname2, count);
}
}
- 文件复制类:
package FileManager;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
//文件复制的顶层窗口
class Frame extends UsualFrame {
private static final long serialVersionUID = 8869083176317715857L;
public Frame(String src, String des) {
super("文件复制进度条", 200, 200, 400, 140);
//添加标签
JLabel jLabelSrc = new JLabel("源文件地址");
add(jLabelSrc);
Text textSrc = new Text(src);
add(textSrc);
JLabel jLabelDes = new JLabel("目标文件地址");
add(jLabelDes);
Text textDes = new Text(des);
add(textDes);
JLabel progress = new JLabel("文件复制进度");
add(progress);
}
}
//文件复制的进度条
class Bar extends JProgressBar {
private static final long serialVersionUID = 6668640864880713050L;
public Bar() {
setMaximum(100);
setValue(0);
setStringPainted(true);
}
}
//文件复制的输入框
class Text extends JTextField {
private static final long serialVersionUID = -6148223959240049121L;
public Text(String name) {
setText(name);
setPreferredSize(new Dimension(100, 30));
}
}
//文件复制类
public class FileCopy extends FileOperate {
private static Frame frame; //顶层窗口
private static Bar bar; //进度条
private long time; //用时
//文件夹的总大小和已经复制了的大小
long allSize = 0;
long copiedSize = 0;
FileCopy(String src, String des) {
super(src, des); //调用基类构造函数
getAllSize(new File(src)); //获得文件(夹)的总大小
frame = new Frame(src, des); //创建顶层窗口
bar = new Bar(); //创建滚动条
frame.add(bar); //滚动条添加到窗口中
}
//进行文件复制
public void copyFile() throws IOException {
copyFile(src, des);
}
//进行文件夹复制
public boolean copyDir() throws IOException {
time = System.currentTimeMillis(); //开始计时
copyDir(src, des);
return true;
}
//进行文件复制
private void copyFile(String src, String des) throws IOException {
File from = new File(src);
File to = new File(des);
try(InputStream fin = new BufferedInputStream(new FileInputStream(from));
OutputStream out = new BufferedOutputStream(new FileOutputStream(to))) {
byte[] flush = new byte[1024]; //每次读取1kb的内容
int len = -1;
while((len = fin.read(flush)) != -1) { //读取源文件
out.write(flush, 0, len); //输出到目标文件
}
out.flush(); //清空缓存区
} catch(FileNotFoundException e) {
e.printStackTrace();
}
}
//进行文件夹复制
private void copyDir(String src, String des) throws IOException {
File from = new File(src);
File to = new File(des);
if(!to.exists()) { //如果没有文件夹则重新创建
to.mkdirs();
}
for(File f : from.listFiles()) { //列举该文件夹下的所有文件
if(f.isFile()) { //如果是文件直接调用文件复制的方法
copyFile(f.getPath(), des + File.separator + f.getName());
copiedSize += f.length(); //累计已经拷贝了的大小
double cur = (double)copiedSize / allSize; //计算bar的进度值
int progress = (int)(cur * 100);
bar.setValue(progress);
if(progress == 100) { //复制完成,弹出带有复制用时消息框
String timeUsed = String.valueOf(System.currentTimeMillis() - time);
JOptionPane.showMessageDialog(frame, "复制完成,共用时" + timeUsed + "ms");
}
}
//否则递归调用本方法
else {
copyDir(f.getPath(), des + File.separator + f.getName());
}
}
}
//获取源文件大小
public void getAllSize(File cur) {
if(cur.isFile())
allSize += cur.length();
if(cur.isDirectory()) {
File[] files = cur.listFiles();
for(File f : files) {
getAllSize(f);
}
}
}
//进行操作
public boolean operate() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try {
copyDir();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
//测试
public static void main(String[] args) throws IOException {
new FileCopy("F://zzz", "F://zzzz").operate();
}
}
class CopyAction extends Action {
private static String name = "复制文件";
private static String lname1 = "请输入源文件地址";
private static String lname2 = "请输入目标文件地址";
private static int count = 2;
public void addAction() {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String s1 = jText1.getText(), s2 = jText2.getText();
new Thread() { //创建线程进行拷贝
public void run() {
FileCopy fc = new FileCopy(s1, s2);
fc.operate();
}
}.start();
}
} );
}
CopyAction() {
super(name, lname1, lname2, count);
}
}
- 文件压缩/解压类:
package FileManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import javax.swing.JOptionPane;
public class FileZip extends FileOperate {
private static final int BUFFER = 1024; //每次压缩的大小
//初始化基类
FileZip(String src, String des) {
super(src, des);
}
//压缩操作的入口
public void compress() throws IOException{
File srcFile = new File(src);
File dstFile = new File(des);
if (!srcFile.exists()) {
throw new FileNotFoundException(src + "不存在!");
}
try(FileOutputStream out = new FileOutputStream(dstFile);
CheckedOutputStream cos = new CheckedOutputStream(out,new CRC32());
ZipOutputStream zipOut = new ZipOutputStream(cos)) {
String baseDir = "";
compress(srcFile, zipOut, baseDir); //递归的压缩操作
}
}
//判断压缩的类型,进行具体操作
private static void compress(File file, ZipOutputStream zipOut, String baseDir) throws IOException{
if (file.isDirectory()) { //文件夹压缩
compressDirectory(file, zipOut, baseDir);
} else { //文件压缩
compressFile(file, zipOut, baseDir);
}
}
//压缩一个目录
private static void compressDirectory(File dir, ZipOutputStream zipOut, String baseDir) throws IOException{
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
compress(files[i], zipOut, baseDir + dir.getName() + "/");
}
}
// 压缩一个文件
private static void compressFile(File file, ZipOutputStream zipOut, String baseDir) throws IOException{
if (!file.exists()){
return;
}
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(baseDir + file.getName());
zipOut.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
zipOut.write(data, 0, count);
}
}finally {
if(null != bis){
bis.close();
}
}
}
//文件解压
public void decompress()throws IOException{
File pathFile = new File(des);
if(!pathFile.exists()){
pathFile.mkdirs();
}
ZipFile zip = new ZipFile(src);
for(Enumeration<? extends ZipEntry> entries = zip.entries();entries.hasMoreElements();){
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = null;
OutputStream out = null;
try {
in = zip.getInputStream(entry);
String outPath = (des+"/"+zipEntryName).replaceAll("\\*", "/");;
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if(!file.exists()){
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory()){
continue;
}
out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
}
finally {
if(null != in){
in.close();
}
if(null != out){
out.close();
}
}
}
zip.close();
}
//测试
public static void main(String[] args)throws Exception{
String pathOrigin = "F:/zzz";
String pathFinal = "F://z";
String pathZip = "F://zz//z.zip";
FileZip fileZip = new FileZip(pathOrigin, pathZip);
fileZip.compress();
fileZip = new FileZip(pathZip, pathFinal);
fileZip.decompress();
}
}
class ZipAction extends Action {
//基本信息
private static String name = "压缩/解压文件";
private static String lname1 = "请输入源地址";
private static String lname2 = "请输入目标地址";
private static int count = 2;
private static String m1 = "压缩/解压成功";
private static String m2 = "压缩/解压失败";
//加入响应事件
public void addAction() {
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String s1 = jText1.getText(), s2 = jText2.getText();
try {
FileZip zip = new FileZip(s1, s2);
if(s1.endsWith(".zip")) { //判断是进行压缩还是解压操作
zip.decompress();
}
else {
zip.compress();
}
JOptionPane.showMessageDialog(frame, m1);
} catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(frame, m2);
}
}
} );
}
ZipAction() {
super(name, lname1, lname2, count);
}
}```