基于Java編寫一個神奇的代碼恢復(fù)工具
一、概述
小C是一名程序猿,他有好多新奇的點子,也樂于把這些變成文字分享給大家。這些分享大部分都與代碼相關(guān),在文章里面把這些代碼全部按本來的結(jié)構(gòu)展示出來也不是一件容易的事!
二、工具展示
這不,最近開發(fā)了一個小工具,界面介紹如下:

三、工具下載地址
procode-simple-0.0.1.jar 提取碼: ca8z
四、運行過程
在輸入框里面輸入待恢復(fù)的代碼,點擊"開始恢復(fù)代碼" 便生成原始項目結(jié)構(gòu)的代碼。

大家可以下載jar,拷貝附件代碼嘗試運行!
五、附件待恢復(fù)代碼
代碼恢復(fù)數(shù)據(jù)框輸入的內(nèi)容為:
goto pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.fly</groupId> <artifactId>procode</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>procode</name> <url>http://maven.apache.org</url> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- 導(dǎo)入swt --> <dependency> <groupId>org.eclipse.platform</groupId> <artifactId>org.eclipse.swt.win32.win32.x86_64</artifactId> <version>3.112.0</version> <exclusions> <exclusion> <groupId>org.eclipse.platform</groupId> <artifactId>org.eclipse.swt.gtk.linux.aarch64</artifactId> </exclusion> <exclusion> <groupId>org.eclipse.platform</groupId> <artifactId>org.eclipse.swt.gtk.linux.arm</artifactId> </exclusion> </exclusions> </dependency> <!-- 導(dǎo)入jface --> <dependency> <groupId>org.eclipse.platform</groupId> <artifactId>org.eclipse.jface</artifactId> <version>3.17.0</version> <exclusions> <exclusion> <groupId>org.eclipse.platform</groupId> <artifactId>org.eclipse.swt</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.eclipse.platform</groupId> <artifactId>org.eclipse.equinox.common</artifactId> <version>3.11.0</version> </dependency> <dependency> <groupId>org.eclipse.platform</groupId> <artifactId>org.eclipse.core.commands</artifactId> <version>3.9.800</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
goto src\main\java\com\fly\procode\core\DateUtil.java
//goto src\main\java\com\fly\procode\core\DateUtil.java
package com.fly.procode.core;
import java.text.SimpleDateFormat;
public class DateUtil
{
public final static String MMDDHHMM = "_MMddHHmm";
public static final String getCurrDateTimeStr(String formatStr)
{
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(System.currentTimeMillis());
}
public static final String getCurrDateTimeStr()
{
return getCurrDateTimeStr(MMDDHHMM);
}
}
//goto src\main\java\com\fly\procode\core\Service.java
package com.fly.procode.core;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import com.fly.procode.process.RunProgress;
/**
* 核心業(yè)務(wù)邏輯類
*/
public class Service extends Observable
{
// 項目源代碼目錄
private String sourcePath;
private RunProgress runProcess;
// 構(gòu)造函數(shù)
public Service()
{
super();
}
public RunProgress getRunProcess()
{
return runProcess;
}
public void setRunProcess(RunProgress runProcess)
{
this.runProcess = runProcess;
}
public String getSourcePath()
{
return sourcePath;
}
public void setSourcePath(String sourcePath)
{
this.sourcePath = sourcePath;
}
// 創(chuàng)建備份文件
public void createBakFile(String bootPath, String bakFileName, List<String> fileFilter, String pwdtext)
{
// InputStream,OutputStream 并不負責文件創(chuàng)建或刪除
// 這部分功能由File來實現(xiàn)
File bakfile = new File(bakFileName);
if (bakfile.exists())
{
bakfile.delete();
}
if (!"".equals(pwdtext))
{
// new FileOutputStream(File file,boolean append)
try (OutputStream fos = new FileOutputStream(bakFileName, false); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "ISO-8859-1")))
{
writer.write("It is a encrypt backup File");
writer.newLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// 備份文件
bakFile(bootPath, bakFileName, fileFilter, pwdtext);
}
// 遞歸備份文件
private void bakFile(String bootPath, String bakFileName, List<String> fileFilter, String pwdtext)
{
File file = new File(sourcePath);
if (file.exists() && file.isDirectory() && !file.getName().startsWith("."))
{
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
{
File f1 = files[i];
if (f1.isDirectory())
{
Service p = new Service();
p.setRunProcess(runProcess);
p.addObserver(runProcess);
p.setSourcePath(f1.getPath());
p.bakFile(bootPath, bakFileName, fileFilter, pwdtext);
}
else if (f1.isFile())
{
if (isExtraFile(f1.getName(), fileFilter))
{
setChanged();
notifyObservers("開始處理文件: " + f1.getName());
List<String> list = new ArrayList<String>();
String text = "http://goto " + f1.getPath().substring(bootPath.length());
list.add(text);
list.addAll(getFiletext(f1.getPath()));
writeFile(list, bakFileName, pwdtext);
}
}
}
}
}
// 以append 方式將text 寫入 bakFile
private void writeFile(List<String> list, String bakFileName, String pwdtext)
{
// 設(shè)置緩沖區(qū)大小為8192 bytes
try (OutputStream os = new FileOutputStream(bakFileName, true); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "ISO-8859-1"), 8192))
{
for (String text : list)
{
writer.write(text);
writer.newLine();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
// 獲取文件內(nèi)容
private List<String> getFiletext(String filePath)
{
// 設(shè)置緩沖區(qū)大小為8192 bytes
List<String> list = new ArrayList<String>();
try (InputStream is = new FileInputStream(filePath); BufferedReader in = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"), 8192))
{
String text;
while ((text = in.readLine()) != null)
{
list.add(text);
}
return list;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
// 是否為需要備份的文件類型
private boolean isExtraFile(String fileName, List<String> fileFilter)
{
for (String postfix : fileFilter)
{
if (fileName.endsWith(postfix))
{
return true;
}
}
return false;
}
// 從備份文件恢復(fù)文件至dir
public void createSourceFile(String bakFile, String dir)
{
File f = new File(bakFile);
String separator = System.getProperty("file.separator");
int beginIndex = bakFile.lastIndexOf(separator) + 1;
int endIndex = bakFile.indexOf("_");
String t;
if (endIndex > 0)
{
t = bakFile.substring(beginIndex, endIndex) + separator;
}
else
{
t = bakFile.substring(beginIndex, bakFile.indexOf(".")) + separator;
}
dir = dir + t;
List<String> list = getFiletext(f.getPath());
BufferedWriter writer = null;
for (String text : list)
{
try
{
if (text.trim().startsWith("http://goto "))
{
// close old file
if (writer != null)
{
writer.close();
}
// creat new file
int pos = text.indexOf("http://goto ") + 7;
File file = new File(dir + text.substring(pos));
file.getParentFile().mkdirs();
OutputStream os = new FileOutputStream(file);
writer = new BufferedWriter(new OutputStreamWriter(os, "8859_1"), 8192);
}
else
{
if (writer != null)
{
writer.write(text);
writer.newLine();
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
if (writer != null)
{
writer.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
//goto src\main\java\com\fly\procode\process\RunProgress.java
package com.fly.procode.process;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import com.fly.procode.core.Service;
/**
*
* 創(chuàng)建代碼進度條線程
*
* @author 00fly
* @version [版本號, 2017年5月3日]
* @see [相關(guān)類/方法]
* @since [產(chǎn)品/模塊版本]
*/
public class RunProgress implements IRunnableWithProgress, Observer
{
private String sourcePath;
private String bakFileName;
private List<String> fileFilter;
private String pwdtext;
private IProgressMonitor monitor;
public RunProgress(String bootPath, String bakFileName, List<String> fileFilter, String pwdtext)
{
super();
this.sourcePath = bootPath;
this.bakFileName = bakFileName;
this.fileFilter = fileFilter;
this.pwdtext = pwdtext;
}
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException
{
// 在當前目錄,創(chuàng)建并運行腳本
try
{
monitor.beginTask("代碼備份", IProgressMonitor.UNKNOWN);
monitor.subTask("代碼備份中......");
creatAndRun(sourcePath, bakFileName, fileFilter, pwdtext, monitor);
monitor.done();
}
catch (Exception e)
{
throw new InvocationTargetException(e.getCause(), e.getMessage());
}
}
// 運行代碼創(chuàng)建程序
private void creatAndRun(String sourcePath, String bakFileName, List<String> fileFilter, String pwdtext, IProgressMonitor monitor)
{
this.monitor = monitor;
Service service = new Service();
service.setRunProcess(this);
service.addObserver(this);
service.setSourcePath(sourcePath);
service.createBakFile(sourcePath, bakFileName, fileFilter, pwdtext);
}
@Override
public void update(Observable observable, Object msg)
{
if (msg instanceof String)
{
monitor.subTask((String)msg);
}
}
}
//goto src\main\java\com\fly\procode\ui\ProCodeToolFrame.java
package com.fly.procode.ui;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
/**
*
* 工具UI簡化版本
*
* @author 00fly
* @version [版本號, 2023年3月3日]
* @see [相關(guān)類/方法]
* @since [產(chǎn)品/模塊版本]
*/
public class ProCodeToolFrame extends JFrame
{
private static final long serialVersionUID = -2145267777297657212L;
JFrame frame = this;
public ProCodeToolFrame()
{
initComponent();
this.setVisible(true);
this.setResizable(true);
this.setAlwaysOnTop(true);
this.setTitle("代碼恢復(fù)工具 V1.0");
this.setBounds(400, 200, 1200, 550);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
try
{
// 設(shè)定用戶界面的外觀
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(this);
}
catch (Exception e)
{
}
}
/**
* 組件初始化
*
* @see [類、類#方法、類#成員]
*/
private void initComponent()
{
// 加載圖標
URL url = getClass().getResource("/image/icon.gif");
if (url != null)
{
this.setIconImage(getToolkit().createImage(url));
}
JTextArea textArea = new JTextArea();
textArea.setToolTipText("請輸入全部待恢復(fù)代碼");
// JTextArea不自帶滾動條,因此就需要把文本區(qū)放到一個滾動窗格中
JScrollPane scroll = new JScrollPane(textArea);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
JButton button = new JButton("開始恢復(fù)代碼");
this.add(scroll, BorderLayout.CENTER);
this.add(button, BorderLayout.SOUTH);
button.addMouseListener(new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent event)
{
try
{
String dir = new File(" ").getCanonicalPath();
createSourceFile(textArea.getText(), dir);
JOptionPane.showMessageDialog(frame, "恢復(fù)文件到目錄: " + dir + " 成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(frame, e.getMessage(), "系統(tǒng)異常", JOptionPane.ERROR_MESSAGE);
}
}
});
}
/**
* 恢復(fù)文件至dir
*
* @param text
* @param dir
*/
private void createSourceFile(String text, String dir)
{
String[] textArr = text.split("\n");
BufferedWriter writer = null;
for (String line : textArr)
{
try
{
if (line.trim().startsWith("http://goto "))
{
// close old file
if (writer != null)
{
writer.close();
}
// creat new file
int pos = line.indexOf("http://goto ") + 7;
File file = new File(dir + line.substring(pos));
file.getParentFile().mkdirs();
OutputStream os = new FileOutputStream(file);
writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8), 8192);
}
else
{
if (writer != null)
{
writer.write(line);
writer.newLine();
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
if (writer != null)
{
writer.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(() -> new ProCodeToolFrame());
}
}
//goto src\main\java\com\fly\procode\ui\ProCodeToolSJ.java
package com.fly.procode.ui;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import com.fly.procode.core.DateUtil;
import com.fly.procode.core.Service;
import com.fly.procode.process.RunProgress;
/**
*
* swt jface版本
*
* @author 00fly
* @version [版本號, 2020年4月24日]
* @see [相關(guān)類/方法]
* @since [產(chǎn)品/模塊版本]
*/
public class ProCodeToolSJ
{
Display display;
Shell shell;
org.eclipse.swt.widgets.List listJava;
org.eclipse.swt.widgets.List listPage;
public ProCodeToolSJ()
{
super();
display = new Display();
shell = new Shell(display, SWT.MIN | SWT.CLOSE | SWT.ON_TOP);
InputStream is = this.getClass().getResourceAsStream("/image/icon.gif");
if (is != null)
{
shell.setImage(new Image(display, is));
}
shell.setText("代碼備份恢復(fù)工具 V1.1.0");
shell.setSize(540, 383);
Rectangle screeRec = display.getBounds();
Rectangle shellRec = shell.getBounds();
if (shellRec.height > screeRec.height)
{
shellRec.height = screeRec.height;
}
if (shellRec.width > screeRec.width)
{
shellRec.width = screeRec.width;
}
shell.setLocation((screeRec.width - shellRec.width) / 2, (screeRec.height - shellRec.height) / 2);
addMenu();
setContent();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
// main
public static void main(String[] args)
{
new ProCodeToolSJ();
}
// Menu set
private void addMenu()
{
Menu m = new Menu(shell, SWT.BAR);
// create a file menu and add an exit item
MenuItem file = new MenuItem(m, SWT.CASCADE);
file.setText("文件(&F)");
file.setAccelerator(SWT.CTRL + 'F');
Menu filemenu = new Menu(shell, SWT.DROP_DOWN);
file.setMenu(filemenu);
MenuItem openMenuItem = new MenuItem(filemenu, SWT.CASCADE);
openMenuItem.setText("最近備份(&O)");
openMenuItem.setAccelerator(SWT.CTRL + 'O');
Menu submenu = new Menu(shell, SWT.DROP_DOWN);
openMenuItem.setMenu(submenu);
MenuItem childItem = new MenuItem(submenu, SWT.PUSH);
childItem.setText("Child");
MenuItem saveMenuItem = new MenuItem(filemenu, SWT.CASCADE);
saveMenuItem.setText("最近恢復(fù)(&S)");
saveMenuItem.setAccelerator(SWT.CTRL + 'S');
Menu submenu2 = new Menu(shell, SWT.DROP_DOWN);
saveMenuItem.setMenu(submenu2);
MenuItem childItem2 = new MenuItem(submenu2, SWT.PUSH);
childItem2.setText("Child2");
new MenuItem(filemenu, SWT.SEPARATOR);
MenuItem exitMenuItem = new MenuItem(filemenu, SWT.PUSH);
exitMenuItem.setText("退出(&X)");
exitMenuItem.setAccelerator(SWT.CTRL + 'X');
exitMenuItem.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent e)
{
System.exit(0);
}
});
// create a Help menu and add an about item
MenuItem help = new MenuItem(m, SWT.CASCADE);
help.setText("幫助(&H)");
help.setAccelerator(SWT.CTRL + 'H');
Menu helpmenu = new Menu(shell, SWT.DROP_DOWN);
help.setMenu(helpmenu);
MenuItem useMenuItem = new MenuItem(helpmenu, SWT.PUSH);
useMenuItem.setText("使用指南(&U)");
new MenuItem(helpmenu, SWT.SEPARATOR);
MenuItem aboutMenuItem = new MenuItem(helpmenu, SWT.PUSH);
aboutMenuItem.setText("關(guān)于工具(&A)");
useMenuItem.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
MessageDialog.openInformation(shell, "使用指南", "請按以下順序操作:" + "\n 文件備份" + "\n 1. 選擇項目源文件的目錄。" + "\n 2. 選擇需要備份的文件類型。" + "\n 3. 選擇備份文件輸出目錄。" + "\n 4. 導(dǎo)出文件。" + "\n " + "\n 文件恢復(fù) " + "\n 1. 到備份目錄下選擇備份文件。" + "\n 2. 選擇備份文件的恢復(fù)目錄。" + "\n 3. 恢復(fù)文件");
}
});
aboutMenuItem.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
MessageDialog.openInformation(shell, "關(guān)于本工具", "代碼備份恢復(fù)工具。\n\nkailin 于2010年5月。");
}
});
shell.setMenuBar(m);
}
public void setContent()
{
TabFolder tabFolder = new TabFolder(shell, SWT.NONE);
tabFolder.setBounds(5, 2, 525, 328);
TabItem item = new TabItem(tabFolder, SWT.NONE);
item.setText(" 代碼備份 ");
item.setControl(new BakPanlTab(tabFolder, SWT.NONE));
TabItem item2 = new TabItem(tabFolder, SWT.NONE);
item2.setText(" 代碼恢復(fù) ");
item2.setControl(new RestorePanlTab(tabFolder, SWT.NONE));
}
// 備份面板
class BakPanlTab extends Composite
{
Button pwdButton;
Text tpwd = new Text(this, SWT.NONE);
public BakPanlTab(Composite c, int style)
{
super(c, style);
Label sourceLabel = new Label(this, SWT.NONE);
sourceLabel.setText("項目源文件目錄:");
sourceLabel.setBounds(20, 30, 100, 18);
final Text tsourcePath = new Text(this, SWT.BORDER);
tsourcePath.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
tsourcePath.setEditable(false);
tsourcePath.setBounds(120, 30, 300, 20);
Button sourceBrowse = new Button(this, SWT.PUSH);
sourceBrowse.setText("選擇");
sourceBrowse.setBounds(430, 30, 70, 20);
sourceBrowse.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
DirectoryDialog dialog = new DirectoryDialog(shell);
dialog.setFilterPath(tsourcePath.getText());
String fileName = dialog.open();
if (fileName != null)
{
if (fileName.endsWith("\\"))
{
tsourcePath.setText(fileName);
}
else
{
tsourcePath.setText(fileName + "\\");
}
// 新源文件目錄被選中,清空密碼
tpwd.setText("");
pwdButton.setEnabled(true);
}
}
});
Label fileTypeLabel = new Label(this, SWT.NONE);
fileTypeLabel.setText("源文件類型:");
fileTypeLabel.setBounds(20, 60, 100, 18);
listJava = new org.eclipse.swt.widgets.List(this, SWT.BORDER | SWT.V_SCROLL | SWT.SIMPLE | SWT.MULTI);
listJava.setBounds(120, 60, 120, 110);
listJava.setToolTipText("選擇需要備份的源文件類型,支持多選!");
String[] fileTypes = {".java", ".xml", ".yml", ".properties", ".sql"};
listJava.setItems(fileTypes);
listPage = new org.eclipse.swt.widgets.List(this, SWT.BORDER | SWT.V_SCROLL | SWT.SIMPLE | SWT.MULTI);
listPage.setBounds(280, 60, 120, 110);
listPage.setToolTipText("選擇需要備份的源文件類型,支持多選!");
String[] fileTypes2 = {".html", ".js", ".css", ".vue", ".jsp"};
listPage.setItems(fileTypes2);
Label pwdLabel = new Label(this, SWT.NONE);
pwdLabel.setText("可選項:");
pwdLabel.setBounds(20, 180, 100, 18);
pwdButton = new Button(this, SWT.PUSH);
pwdButton.setText("設(shè)置密碼");
pwdButton.setBounds(120, 180, 100, 20);
pwdButton.setEnabled(false);
pwdButton.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
InputDialog dlg = new InputDialog(shell, "帶密碼備份", "請輸入8位密碼(包括字母,數(shù)字和字符):", "", new LengthValidator());
if (dlg.open() == Window.OK)
{
tpwd.setText(dlg.getValue());
MessageDialog.openInformation(shell, "恭喜你", "密碼設(shè)置成功!");
}
}
});
Label bakeLabel = new Label(this, SWT.NONE);
bakeLabel.setText("備份至目錄:");
bakeLabel.setBounds(20, 210, 100, 18);
final Text tbakPath = new Text(this, SWT.BORDER);
tbakPath.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
tbakPath.setEditable(false);
tbakPath.setText(new File(" ").getAbsolutePath().trim());
tbakPath.setBounds(120, 210, 300, 20);
Button bakBrowse = new Button(this, SWT.PUSH);
bakBrowse.setText("選擇");
bakBrowse.setBounds(430, 210, 70, 20);
bakBrowse.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
DirectoryDialog dialog = new DirectoryDialog(shell);
dialog.setFilterPath(tbakPath.getText());
String fileName = dialog.open();
if (fileName != null)
{
if (fileName.endsWith("\\"))
{
tbakPath.setText(fileName);
}
else
{
tbakPath.setText(fileName + "\\");
}
}
}
});
Button bakButton = new Button(this, SWT.PUSH);
bakButton.setText("開始備份");
bakButton.setBounds(220, 250, 100, 40);
bakButton.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
if ("".equals(tsourcePath.getText()))
{
MessageDialog.openWarning(shell, "警告", "項目源文件目錄不可為空!");
return;
}
if (listJava.getSelectionCount() + listPage.getSelectionCount() < 1)
{
MessageDialog.openError(shell, "警告", "請選擇源文件類型,支持多選!");
listJava.setFocus();
return;
}
String sourcePath = tsourcePath.getText();
String bakFileName = tbakPath.getText() + new File(sourcePath).getName() + DateUtil.getCurrDateTimeStr() + ".bak";
try
{
List<String> fileTypes = new ArrayList<String>();
for (String it : listJava.getSelection())
{
fileTypes.add(it);
}
for (String it : listPage.getSelection())
{
fileTypes.add(it);
}
String pwdtext = tpwd.getText();
IRunnableWithProgress runnable = new RunProgress(sourcePath, bakFileName, fileTypes, pwdtext);
new ProgressMonitorDialog(shell).run(true, false, runnable);
String message = "創(chuàng)建明文備份文件 " + bakFileName + " 成功!";
if (!"".equals(pwdtext))
{
message = "創(chuàng)建加密備份文件 " + bakFileName + " 成功!";
}
MessageDialog.openInformation(shell, "提示", message);
}
catch (InvocationTargetException e)
{
MessageDialog.openError(shell, "警告", e.getMessage());
}
catch (InterruptedException e)
{
MessageDialog.openInformation(shell, "Cancelled", "刷新操作被用戶取消!");
}
catch (RuntimeException e)
{
MessageDialog.openError(shell, "錯誤", "創(chuàng)建備份文件 " + bakFileName + " 失??!");
}
if (MessageDialog.openConfirm(shell, "查看備份文件", "處理完成,是否直接查看文件?"))
{
try
{
Desktop.getDesktop().open(new File(bakFileName).getParentFile());
}
catch (IOException e)
{
}
}
}
});
}
// 密碼長度驗證
class LengthValidator implements IInputValidator
{
@Override
public String isValid(String newText)
{
int len = newText.length();
if (len < 8)
{
return "長度少于8位";
}
if (len > 8)
{
return "長度大于8位";
}
return null;
}
}
}
// 恢復(fù)面板
class RestorePanlTab extends Composite
{
public RestorePanlTab(Composite c, int style)
{
super(c, style);
Label bakeLabel = new Label(this, SWT.NONE);
bakeLabel.setText("選擇備份文件:");
bakeLabel.setBounds(20, 30, 100, 18);
final Text tbakPath = new Text(this, SWT.BORDER);
tbakPath.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
tbakPath.setEditable(false);
tbakPath.setBounds(120, 30, 300, 20);
Button bakBrowse = new Button(this, SWT.PUSH);
bakBrowse.setText("選擇");
bakBrowse.setBounds(430, 30, 70, 20);
bakBrowse.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);
fileDialog.setText("選擇文件");
String[] filterExt = {"*.bak"};
fileDialog.setFilterExtensions(filterExt);
String selected = fileDialog.open();
if (selected == null)
{
return;
}
tbakPath.setText(selected);
}
});
Label sourceLabel = new Label(this, SWT.NONE);
sourceLabel.setText("恢復(fù)至目錄:");
sourceLabel.setBounds(20, 100, 100, 18);
final Text tsourcePath = new Text(this, SWT.BORDER);
tsourcePath.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
tsourcePath.setEditable(false);
tsourcePath.setText(new File(" ").getAbsolutePath().trim());
tsourcePath.setBounds(120, 100, 300, 20);
Button sourceBrowse = new Button(this, SWT.PUSH);
sourceBrowse.setText("選擇");
sourceBrowse.setBounds(430, 100, 70, 20);
sourceBrowse.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
DirectoryDialog dialog = new DirectoryDialog(shell);
dialog.setFilterPath(tsourcePath.getText());
String fileName = dialog.open();
if (fileName != null)
{
if (fileName.endsWith("\\"))
{
tsourcePath.setText(fileName);
}
else
{
tsourcePath.setText(fileName + "\\");
}
}
}
});
Button resetButton = new Button(this, SWT.PUSH);
resetButton.setText("開始恢復(fù)");
resetButton.setBounds(220, 170, 100, 40);
resetButton.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent event)
{
if ("".equals(tbakPath.getText()) || "".equals(tsourcePath.getText()))
{
MessageDialog.openWarning(shell, "警告", "備份文件或恢復(fù)目錄不可為空!");
}
else
{
String dir = tsourcePath.getText();
try
{
new Service().createSourceFile(tbakPath.getText(), dir);
MessageDialog.openInformation(shell, "提示", "恢復(fù)文件到目錄: " + dir + " 成功!");
}
catch (RuntimeException e)
{
MessageDialog.openError(shell, "錯誤", "恢復(fù)文件失敗,請重新檢查備份文件!");
}
}
}
});
}
}
}六、使用總結(jié)
下載 jar
拷貝代碼
粘帖代碼
一鍵恢復(fù)
以上就是基于Java編寫一個神奇的代碼恢復(fù)工具的詳細內(nèi)容,更多關(guān)于Java代碼恢復(fù)工具的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring之底層架構(gòu)核心概念Environment及用法詳解
這篇文章主要介紹了Spring之底層架構(gòu)核心概念-Environment,本文結(jié)合示例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-12-12
Spring Cloud Netflix架構(gòu)淺析(小結(jié))
這篇文章主要介紹了Spring Cloud Netflix架構(gòu)淺析(小結(jié)),詳解的介紹了Spring Cloud Netflix的概念和組件等,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01
IDEA生成可運行jar包(包含第三方j(luò)ar包)流程詳解
這篇文章主要介紹了IDEA生成可運行jar包(包含第三方j(luò)ar包)流程詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11
Mybatis的collection三層嵌套查詢方式(驗證通過)
這篇文章主要介紹了Mybatis的collection三層嵌套查詢方式(驗證通過),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03

