IT俱乐部 Java 基于Java编写一个神奇的代码恢复工具

基于Java编写一个神奇的代码恢复工具

一、概述

小C是一名程序猿,他有好多新奇的点子,也乐于把这些变成文字分享给大家。这些分享大部分都与代码相关,在文章里面把这些代码全部按本来的结构展示出来也不是一件容易的事!

二、工具展示

这不,最近开发了一个小工具,界面介绍如下:

三、工具下载地址

procode-simple-0.0.1.jar 提取码: ca8z 

四、运行过程

在输入框里面输入待恢复的代码,点击”开始恢复代码” 便生成原始项目结构的代码。

大家可以下载jar,拷贝附件代码尝试运行!

五、附件待恢复代码

代码恢复数据框输入的内容为:

goto pom.xml

goto srcmainjavacomflyprocodecoreDateUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
//goto srcmainjavacomflyprocodecoreDateUtil.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 srcmainjavacomflyprocodecoreService.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;
 
/**
 * 核心业务逻辑类
 */
public class Service extends Observable
{
    // 项目源代码目录
    private String sourcePath;
     
    private RunProgress runProcess;
     
    // 构造函数
    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;
    }
     
    // 创建备份文件
    public void createBakFile(String bootPath, String bakFileName, List fileFilter, String pwdtext)
    {
        // InputStream,OutputStream 并不负责文件创建或删除
        // 这部分功能由File来实现
        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 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  list = new ArrayList();
                        String text = "//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 list, String bakFileName, String pwdtext)
    {
        // 设置缓冲区大小为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();
        }
    }
     
    // 获取文件内容
    private List getFiletext(String filePath)
    {
        // 设置缓冲区大小为8192 bytes
        List list = new ArrayList();
        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 fileFilter)
    {
        for (String postfix : fileFilter)
        {
            if (fileName.endsWith(postfix))
            {
                return true;
            }
        }
        return false;
    }
     
    // 从备份文件恢复文件至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 list = getFiletext(f.getPath());
        BufferedWriter writer = null;
        for (String text : list)
        {
            try
            {
                if (text.trim().startsWith("//goto "))
                {
                    // close old file
                    if (writer != null)
                    {
                        writer.close();
                    }
                    // creat new file
                    int pos = text.indexOf("//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 srcmainjavacomflyprocodeprocessRunProgress.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;
 
/**
 *
 * 创建代码进度条线程
 *
 * @author 00fly
 * @version [版本号, 2017年5月3日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class RunProgress implements IRunnableWithProgress, Observer
{
    private String sourcePath;
     
    private String bakFileName;
     
    private List fileFilter;
     
    private String pwdtext;
     
    private IProgressMonitor monitor;
     
    public RunProgress(String bootPath, String bakFileName, List 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
    {
        // 在当前目录,创建并运行脚本
        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());
        }
    }
     
    // 运行代码创建程序
    private void creatAndRun(String sourcePath, String bakFileName, List 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 srcmainjavacomflyprocodeuiProCodeToolFrame.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 [相关类/方法]
 * @since [产品/模块版本]
 */
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("代码恢复工具 V1.0");
        this.setBounds(400, 200, 1200, 550);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        try
        {
            // 设定用户界面的外观
            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("请输入全部待恢复代码");
         
        // JTextArea不自带滚动条,因此就需要把文本区放到一个滚动窗格中
        JScrollPane scroll = new JScrollPane(textArea);
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
         
        JButton button = new JButton("开始恢复代码");
        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, "恢复文件到目录: " + dir + " 成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
                }
                catch (Exception e)
                {
                    JOptionPane.showMessageDialog(frame, e.getMessage(), "系統异常", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }
     
    /**
     * 恢复文件至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("//goto "))
                {
                    // close old file
                    if (writer != null)
                    {
                        writer.close();
                    }
                    // creat new file
                    int pos = line.indexOf("//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 srcmainjavacomflyprocodeuiProCodeToolSJ.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 [相关类/方法]
 * @since [产品/模块版本]
 */
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("代码备份恢复工具 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("最近恢复(&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("关于工具(&A)");
        useMenuItem.addSelectionListener(new SelectionAdapter()
        {
            @Override
            public void widgetSelected(SelectionEvent event)
            {
                MessageDialog.openInformation(shell, "使用指南", "请按以下顺序操作:" + "n 文件备份" + "n 1. 选择项目源文件的目录。" + "n 2. 选择需要备份的文件类型。" + "n 3. 选择备份文件输出目录。" + "n 4. 导出文件。" + "n " + "n 文件恢复 " + "n 1. 到备份目录下选择备份文件。" + "n 2. 选择备份文件的恢复目录。" + "n 3. 恢复文件");
            }
        });
        aboutMenuItem.addSelectionListener(new SelectionAdapter()
        {
            @Override
            public void widgetSelected(SelectionEvent event)
            {
                MessageDialog.openInformation(shell, "关于本工具", "代码备份恢复工具。nnkailin 于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(" 代码恢复 ");
        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("设置密码");
            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位密码(包括字母,数字和字符):", "", new LengthValidator());
                    if (dlg.open() == Window.OK)
                    {
                        tpwd.setText(dlg.getValue());
                        MessageDialog.openInformation(shell, "恭喜你", "密码设置成功!");
                    }
                }
            });
            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()  fileTypes = new ArrayList();
                        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 = "创建明文备份文件 " + bakFileName + " 成功!";
                        if (!"".equals(pwdtext))
                        {
                            message = "创建加密备份文件 " + 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, "错误", "创建备份文件 " + 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位";
                }
                return null;
            }
        }
    }
     
    // 恢复面板
    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("恢复至目录:");
            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("开始恢复");
            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, "警告", "备份文件或恢复目录不可为空!");
                    }
                    else
                    {
                        String dir = tsourcePath.getText();
                        try
                        {
                            new Service().createSourceFile(tbakPath.getText(), dir);
                            MessageDialog.openInformation(shell, "提示", "恢复文件到目录: " + dir + " 成功!");
                        }
                        catch (RuntimeException e)
                        {
                            MessageDialog.openError(shell, "错误", "恢复文件失败,请重新检查备份文件!");
                        }
                    }
                }
            });
        }
    }
}

六、使用总结

下载 jar

拷贝代码

粘帖代码

一键恢复

以上就是基于Java编写一个神奇的代码恢复工具的详细内容,更多关于Java代码恢复工具的资料请关注IT俱乐部其它相关文章!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/10800.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部