posts - 23, comments - 0, trackbacks - 0, articles - 3
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

开发插件实战

Posted on 2008-08-18 17:04 beauty9235 阅读(128) 评论(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推荐




只有注册用户登录后才能发表评论。


网站导航: