posts - 23, comments - 0, trackbacks - 0, articles - 3
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          開發插件實戰

          Posted on 2008-08-18 17:04 beauty9235 閱讀(140) 評論(0)  編輯  收藏

          作者: beauty9235  鏈接:http://beauty9235.javaeye.com/blog/229629  發表時間: 2008年07月21日

          聲明:本文系JavaEye網站發布的原創博客文章,未經作者書面許可,嚴禁任何網站轉載本文,否則必將追究法律責任!

          最近由于公司要求開發一個小小的插件,用來改變文件名字
          簡單的說,就是讀取一個csv文件,里面只有兩列
          如:test.csv
          "OldName","NewName"
          "test1.eps","1.eps"
          "test2.eps","2.eps"
          "test3.tif","3.eps"
          然后用戶通過界面選擇csv文件,選擇源文件目錄,選擇目的文件目錄,選好再按一個鍵對原來文件按新的文件名輸出。

          我開始拿到蒙了,因為自己沒有搞過呀,經過查資料,自己研究,搞定。
          下面開始我們的實戰吧。

          工欲善其事,必須利其器

          首選搭建好開發環境。

          1.安裝MyEclipse 6.0
          2.安裝打包工具
             net.sf.fjep.fatjar_0.0.27.zip
             我是解壓到 MyEclipse 6.0\fjep\eclipse\plugins
              在MyEclipse 6.0\eclipse\links
           建fjep.link 里,添加 path=C:\\Program Files\\MyEclipse 6.0\\fjep
          3.重啟myeclipse
           我們的開發環境就搞定啦
           重啟后Window->Preferences可以看到 Fat Jar Preferences
              說明你安裝成功
           
          下面開始我們的項目
          1.新建Plug-in Project名字自己取Demo
            建好后可以看到結構Demo --src
                                   --bin
          2.新建log4j.properties
           log4j.rootLogger=DEBUG, stdout
           log4j.appender.stdout=org.apache.log4j.ConsoleAppender
           log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
           log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n
           log4j.logger.java.sql.PreparedStatement=DEBUG
          3.新建cvs.properties  
              csv.field.key=OldName, NewName
          4.編輯NewRenamer.java


          import java.io.File;
          import java.io.IOException;
          import java.sql.Connection;
          import java.sql.DriverManager;
          import java.sql.ResultSet;
          import java.sql.Statement;

          import org.apache.commons.configuration.Configuration;
          import org.apache.commons.configuration.PropertiesConfiguration;
          import org.apache.commons.io.FileUtils;
          import org.apache.commons.lang.StringUtils;
          import org.apache.commons.logging.Log;
          import org.apache.commons.logging.LogFactory;
          import org.eclipse.swt.SWT;
          import org.eclipse.swt.custom.CLabel;
          import org.eclipse.swt.graphics.Color;
          import org.eclipse.swt.graphics.Point;
          import org.eclipse.swt.layout.GridData;
          import org.eclipse.swt.layout.GridLayout;
          import org.eclipse.swt.widgets.Button;
          import org.eclipse.swt.widgets.DirectoryDialog;
          import org.eclipse.swt.widgets.Display;
          import org.eclipse.swt.widgets.FileDialog;
          import org.eclipse.swt.widgets.Shell;
          import org.eclipse.swt.widgets.Table;
          import org.eclipse.swt.widgets.TableColumn;
          import org.eclipse.swt.widgets.TableItem;
          public class Renamer
          {                                                
           private static final String CVS_PROPERTIES = "cvs.properties";
           
           Log log = LogFactory.getLog(Renamer.class);
           private Shell sShell = null;
           private Button btnSourceDir = null;
           private CLabel labSourceDir = null;
           
           private Button btnDestinationDir = null;
           private CLabel labDestinationDir = null;
           
           private Button btnCSVFile = null;
           private CLabel labCSVFile = null;
           
           String openDirPathFlag = "openDirPath";  //  @jve:decl-index=0:
           private Table tabPreview = null;
           private Button processIt = null;
           
           //private Button restoreIt = null;
           //private Button flashRestore = null;
           int runTime = 1000 * 10;
           
           private void createSShell() {
            GridData gridData = new GridData();
           
            gridData.horizontalSpan = 7;
            gridData.verticalAlignment = GridData.FILL;
           
            gridData.verticalSpan = 3;
            gridData.grabExcessVerticalSpace = true;
            gridData.horizontalAlignment = GridData.FILL;
           
            GridLayout gridLayout = new GridLayout();
            gridLayout.numColumns = 8;
           
            sShell = new Shell();
            sShell.setText("Shell");
            sShell.setLayout(gridLayout);
            sShell.setSize(new Point(800, 500));
           
           
            btnCSVFile = new Button(sShell, SWT.NONE);
            btnCSVFile.setText("CSV");
            btnCSVFile.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
             public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
              //清掉以前的顯示結果
              tabPreview.removeAll();
              //path part
              String openDirPath = (String)btnCSVFile.getData(openDirPathFlag);
              FileDialog dd = new FileDialog(sShell, SWT.NONE);//用來顯示一個目錄對話
              dd.setFilterPath(openDirPath);
              dd.setText("CVS file");
              String cvsPath = dd.open();
              cvsPath = cvsPath == null ? "" : cvsPath;
              btnCSVFile.setData(openDirPathFlag,cvsPath);
                 labCSVFile.setText(cvsPath);
                 if(StringUtils.isEmpty(cvsPath)) return;
               //得到csv文件
             
              String csvDir=StringUtils.substringBeforeLast(cvsPath, "\\");
              String csvFileName=StringUtils.substringAfterLast(cvsPath, "\\");
              String csvFileNameNotSuffix=StringUtils.replace(csvFileName, ".csv", "");
              log.debug(csvDir);
              log.debug(csvFileNameNotSuffix);
              try {
               Configuration config = new PropertiesConfiguration(CVS_PROPERTIES);
               String[] aryFields = config.getStringArray("csv.field.key"); 
              
               // 加載驅動
               Class.forName("org.relique.jdbc.csv.CsvDriver");

               // 定位文件夾位置

               Connection conn = DriverManager
                 .getConnection("jdbc:relique:csv:"+csvDir);

               Statement stmt = conn.createStatement();

               // 注意 csvFileNameNotSuffix 就是cvs文件
              
               ResultSet results = stmt
                 .executeQuery("SELECT * FROM "+csvFileNameNotSuffix);

               while (results.next()) {
                String showname = results.getString(aryFields[0]);
                      String destName = results.getString(aryFields[1]);
                      TableItem item = new TableItem(tabPreview, SWT.NONE);
                      item.setText(0,showname);
                   TabItemData itemData = new TabItemData(cvsPath,"",showname,"",destName);
                   item.setData("itemData",itemData);
                      item.setText(1,destName); 
               }
               results.close();
               stmt.close();
               conn.close();

              } catch (Exception e1) {

               log.debug(e1);
              }

             }
            });
            labCSVFile = new CLabel(sShell, SWT.NONE);
            labCSVFile.setText("please choose CSV");
           
           
           
           
           
            btnSourceDir = new Button(sShell, SWT.NONE);
            btnSourceDir.setText("source");
            btnSourceDir
            .addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
             public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
              String csvFile = (String)btnCSVFile.getData(openDirPathFlag);
              if(StringUtils.isEmpty(csvFile)) return;//必須先有csv文件

              //path part
              String openDirPath = (String)btnSourceDir.getData(openDirPathFlag);
             
              DirectoryDialog dd = new DirectoryDialog(sShell, SWT.NONE);//用來顯示一個目錄對話
              dd.setFilterPath(openDirPath);
              dd.setText("Souce Dir");
              String sourcePath = dd.open();
              sourcePath = sourcePath == null ? "" : sourcePath;
             
              btnSourceDir.setData(openDirPathFlag,sourcePath);
                 labSourceDir.setText(sourcePath);
                
                          int tabLength = tabPreview.getItems().length;
             
              for(int i=0;i<tabLength;i++){
               TableItem item = tabPreview.getItem(i);
              
               TabItemData itemData = (TabItemData)item.getData("itemData");
               itemData.setSourceDir(sourcePath+"\\");//把源目錄加進去
              
               item.setData("itemData",itemData);

               System.out.println(i+":" +tabPreview.getItems().length + "\n" + itemData);
               if(new File(itemData.getSourceFilePath()).exists()){
                item.setBackground(new Color( sShell.getDisplay(), 0, 255, 128 ));
               }
              
              }
             
             
             }
            });
           
           
           
            labSourceDir = new CLabel(sShell, SWT.NONE);
            labSourceDir.setText("please choose directory");
           
            btnDestinationDir = new Button(sShell, SWT.NONE);
            btnDestinationDir.setText("destination");
            btnDestinationDir.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
             public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
              String openDirPath = (String)btnDestinationDir.getData(openDirPathFlag);
             
              DirectoryDialog dd = new DirectoryDialog(sShell, SWT.NONE);
              dd.setFilterPath(openDirPath);
              dd.setText("destination dir");
              String path = dd.open();
              btnDestinationDir.setData(openDirPathFlag,path);
              labDestinationDir.setText(path);
             }
            });
            labDestinationDir = new CLabel(sShell, SWT.NONE);
            labDestinationDir.setText("please choose directory");
           
           
           
           
           
           
            processIt = new Button(sShell, SWT.NONE);
            processIt.setText(" process it ");
            processIt.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
             public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
              //得到目的路徑
              String descPath = (String)btnDestinationDir.getData(openDirPathFlag);
              if(StringUtils.isEmpty(descPath)) return;
             
              int tabLength = tabPreview.getItems().length;
              descPath += "\\";
              for(int i=0;i<tabLength;i++){
               TableItem item = tabPreview.getItem(i);
               TabItemData itemData = (TabItemData)item.getData("itemData");
              
               itemData.setDestinationDir(descPath);
              
               System.out.println(i+":" +tabPreview.getItems().length + "\n" + itemData);
               if(new File(itemData.getSourceFilePath()).exists()){
               try {
                FileUtils.copyFile(new File(itemData.getSourceFilePath()),new File(itemData.getDestinationFilePath()));
                item.setBackground(new Color( sShell.getDisplay(), 184, 109, 109 ));
               } catch (IOException e1) {
                System.out.println("e1:" + e1);
               }
               }
              }
             }
            });
           

            tabPreview = new Table(sShell, SWT.NONE);
            tabPreview.setHeaderVisible(true);
            tabPreview.setLayoutData(gridData);
            tabPreview.setLinesVisible(true);
           
            TableColumn colSource = new TableColumn(tabPreview, SWT.NONE);
            colSource.setWidth(350);
            colSource.setText("source");
           
            TableColumn colDestination = new TableColumn(tabPreview, SWT.NONE);
            colDestination.setWidth(350);
            colDestination.setText("destination");
           
           }
           
           
              public static void main(String[] args)
              {
              
               Display display = Display.getDefault();
               Renamer thisClass = new Renamer();
            thisClass.createSShell();
            thisClass.sShell.open();

            while (!thisClass.sShell.isDisposed()) {
             if (!display.readAndDispatch())
              display.sleep();
            }
            display.dispose();
           
               }
          }

           

          5.編輯BaseObject.java


          import org.apache.commons.lang.builder.HashCodeBuilder;
          import org.apache.commons.lang.builder.ToStringStyle;
          import org.apache.commons.lang.builder.ToStringBuilder;
          import org.apache.commons.lang.builder.EqualsBuilder;
          import org.apache.commons.logging.Log;
          import org.apache.commons.logging.LogFactory;

          import java.io.Serializable;

          public class BaseObject implements Serializable {

              public static final Log log = LogFactory.getLog(BaseObject.class);

              public String toString() {
                  return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
              }

              public boolean equals(Object o) {
                  return EqualsBuilder.reflectionEquals(this, o);
              }

              public int hashCode() {
                  return HashCodeBuilder.reflectionHashCode(this);
              }


          }
          6.編輯TabItemData.java


          public class TabItemData extends BaseObject{
           String sourceDir = "";
           String csvFile = "";
           String fileInSourceDir = "";
           String destinationDir = "";
           String fileInDestinationDir = "";
           
           
           public TabItemData(String csvFile,String sourceDir,
             String fileInSourceDir,
             String destinationDir,
             String fileInDestinationDir){
            this.csvFile = csvFile;
            this.sourceDir = sourceDir;
            this.fileInSourceDir = fileInSourceDir;
            this.destinationDir = destinationDir;
            this.fileInDestinationDir = fileInDestinationDir;
           
           }
           
           
           public String getCsvFile() {
            return csvFile;
           }

           public void setCsvFile(String csvFile) {
            this.csvFile = csvFile;
           }

           public String getSourceFilePath(){
            return this.getSourceDir() + this.getFileInSourceDir();
           }
           
           public String getDestinationFilePath(){
            return this.getDestinationDir() + this.getFileInDestinationDir();
           }
           
           public String getDestinationDir() {
            return destinationDir;
           }
           public void setDestinationDir(String destinationDir) {
            this.destinationDir = destinationDir;
           }
           public String getFileInDestinationDir() {
            return fileInDestinationDir;
           }
           public void setFileInDestinationDir(String fileInDestinationDir) {
            this.fileInDestinationDir = fileInDestinationDir;
           }
           public String getFileInSourceDir() {
            return fileInSourceDir;
           }
           public void setFileInSourceDir(String fileInSourceDir) {
            this.fileInSourceDir = fileInSourceDir;
           }
           public String getSourceDir() {
            return sourceDir;
           }
           public void setSourceDir(String sourceDir) {
            this.sourceDir = sourceDir;
           }
           
           

          }


          7.上面我們把一切都編好了
            然后選擇項目->右健->Fat jar->選擇main class [NewRenamer] ->finish就生成夾包了
          8.編輯批處理文件 
          run.bat 里面加
          start javaw -jar Demo_fat.jar

          即可運行啦

          說明:
          jdk 1.42
          這是本項目必須的jar包
          commons-collections-3.0.jar
          commons-configuration-1.5.jar
          commons-io-1.2.jar
          commons-lang-2.4.jar
          commons-logging.jar
          csvjdbc.jar
          log4j-1.2.9.jar

           


          本文的討論也很精彩,瀏覽討論>>


          JavaEye推薦




          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 昭平县| 安化县| 甘德县| 阳谷县| 莱州市| 温泉县| 湖北省| 中超| 来凤县| 洪泽县| 涟源市| 诸暨市| 明光市| 桂阳县| 永仁县| 柳江县| 札达县| 黑水县| 会东县| 华容县| 洪雅县| 黄冈市| 福建省| 山西省| 鄂尔多斯市| 荥经县| 阳江市| 黄骅市| 米脂县| 原阳县| 河曲县| 西乌| 乐至县| 龙泉市| 正安县| 积石山| 丹江口市| 日喀则市| 左权县| 盱眙县| 蓬莱市|