編寫更少量的代碼:使用apache commons工具類庫


 

 

在看項目代碼的過程中你會發現某些代碼完全可以直接用開源框架來減少代碼量的,如一些帶有util的工具類、一些常用的io操作等;

研究發現一般的應用程序每 1,000 行代碼就包含 20 到 250 個 bug!這個度量被稱作缺陷密度。因此可得出一個重要的結論:更少的代碼意味着更少的缺陷。

個人認為在項目開發過程中最好能有這樣的習慣:能用開源框架(開源框架基本都是眾多程序員智慧的結晶,經得住考驗)就盡量用,最大限度地減少編碼量;即當編碼處理一些業務邏輯時首先想想或找找有沒相關的開源框架,有適合的就用。

重視Apache Commons

公司的各個應用下基本都有Apache Commons下的一些jar包,但在開發過程中習慣性用到這些工具包的童鞋可能比較少(經常使用到這些jar包的童鞋可以忽視),其實用好Apache Commons下工具集和幫助集可以減少好些編碼量。 Apache Commons包含了很多開源的工具,用於解決平時編程經常會遇到的問題,減少重復編碼。

 

 

Commons-configuration

  1. 如果要使用configuration這個包,首先要保證使用JDK1.2以上,還要引入如下jar包

 

commons-beanutils

commons-lang

commons-logging

commons-collections

commons-digester

commons-codec

commons-jxpath

 

  1. commons-configuration最新的版本是1.5,這個工具是用來幫助處理配置文件的,支持很多種存儲方式
1.    Properties files
2.    XML documents
3.    Property list files (.plist)
4.    JNDI
5.    JDBC Datasource
6.    System properties
7.    Applet parameters
8.    Servlet parameters

最主要的作用是讀取資源文件,每一種文件格式都有一個對應的類,如下

 

properties文件--PropertiesConfiguration類;

xml文件—XMLConfiguration;

.ini文件—INIConfiguration;

.plist文件—PropertyListConfiguration;

 

還可以從JNDI中讀取properties—JNDIConfiguration;當然還可以使用system的properties--SystemConfiguration

  1. 用Properties讀取配置文件

usergui.properties(放在類根路徑下面): 

colors.background = #FFFFFF
colors.foreground = #000080
window.width = 500
window.height = 300
keys=cn,com,org,uk,edu,jp,hk

 

(1) 一般寫法:

public static void readProperties() {
        InputStream in = null;
        try {
            in = new BufferedInputStream((new ClassPathResource(
                    "usergui.properties")).getInputStream());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Properties p = new Properties();
        try {
            p.load(in);
            System.out.println(p.getProperty("colors.background"));
        } catch (IOException e) {
        }
    }

 

(2) 另一種ResourceBundle方式: 

public static void readProperties() {
        Locale locale = Locale.getDefault();
        ResourceBundlelocalResource = ResourceBundle.getBundle("usergui", locale);
        String value = localResource.getString("colors.background");
        System.out.println("ResourceBundle: " + value);
    }

 

(3) 使用PropertiesConfiguration

public static void loadProperty() {

        try {
            PropertiesConfigurationconfig = new PropertiesConfiguration(
                    "usergui.properties");
            config.setProperty("colors.background", "#00000F");// 更改值
            config.save();
            config.save("usergui.backup.properties");// save a copy
            System.out.println(config.getProperty("colors.background"));
            System.out.println(config.getInt("window.width"));
            String[] keys = config.getStringArray("keys");
            List key2 = config.getList("keys");
            for (int i = 0; i < keys.length; i++) {
                System.out.println(keys[i]);
            }

            for (Object str : key2) {
                System.out.println(str.toString());
            }
        } catch (Exception e) {
        }
    }

 

 

Commons-FileUpload:

 詳細案例請參考 文件上傳---普通文件和url文件

 

 

Commons DbUtils

這個工具並不是現在流行的OR-Mapping工具(比如Hibernate),只是簡化數據庫操作,比如

QueryRunner run = new QueryRunner(dataSource);
// Execute the query and get the results back from the handler
Object[] result = (Object[]) run.query("SELECT * FROM Person WHERE name=?", "John Doe");

commons-dbutils是 Apache 組織提供的一個開源 JDBC 工具類庫,對傳統操作數據庫的類進行二次封裝,可以把結果集轉化成List。

項目主頁: http://commons.apache.org/dbutils/ 

文檔地址: http://commons.apache.org/dbutils/examples.html 

下載地址:http://commons.apache.org/downloads/download_dbutils.cgi 

(1) org.apache.commons.dbutils

DbUtils  : 提供如關閉連接、裝載 JDBC 驅動程序等常規工作的工具類

QueryRunner : 該類簡單化了 SQL 查詢,它與ResultSetHandler組合在一起使用可以完成大部分的數據庫操作,能夠大大減少編碼量。

QueryLoader : 屬性文件加載器,主要用於加載屬性文件中的 SQL 到內存中。

(2) org.apache.commons.dbutils.handlers

ArrayHandler:將ResultSet中第一行的數據轉化成對象數組

ArrayListHandler將ResultSet中所有的數據轉化成List,List中存放的是Object[] 

BeanHandler:將ResultSet中第一行的數據轉化成類對象

BeanListHandler:將ResultSet中所有的數據轉化成List,List中存放的是類對象

ColumnListHandler:將ResultSet中某一列的數據存成List,List中存放的是Object對象

KeyedHandler:將ResultSet中存成映射,key為某一列對應為Map。Map中存放的是數據

MapHandler:將ResultSet中第一行的數據存成Map映射

MapListHandler:將ResultSet中所有的數據存成List。List中存放的是Map 

ScalarHandler:將ResultSet中一條記錄的其中某一列的數據存成Object 

(3) org.apache.commons.dbutils.wrappers

SqlNullCheckedResultSet:該類是用來對sql語句執行完成之后的的數值進行null的替換。

StringTrimmedResultSet:去除ResultSet中中字段的左右空格。Trim()

  1. 例子
public class TestDbUtils {

    /**
     * 
     * BeanListHandler:將ResultSet中所有的數據轉化成List,List中存放的是類對象
     */

    public static void getBeanListData() {
        Connection conn = getConnection();
        QueryRunner qr = new QueryRunner();
        try {
            ResultSetHandler rsh = new BeanHandler(TUser.class);
            TUser usr = (TUser) qr.query(conn,
                    "SELECTid,username,gender FROM t_user WHERE id=10000", rsh);
            System.out.println(StringUtils.center("findById", 50, '*'));
            // System.out.println("id=" + usr.getId() + " name=" +
            // usr.getUsername() + " gender=" + usr.getGender());
            List results = (List) qr.query(conn,
                    "SELECT id,username,gender FROM t_user",
                    new BeanListHandler(TUser.class));
            System.out.println(StringUtils.center("findAll", 50, '*'));
            for (int i = 0; i < results.size(); i++) {
                TUser user = (TUser) results.get(i);
                // System.out.println("id=" + user.getId() + "  name=" +
                // user.getUsername() + "  gender=" + user.getGender());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(conn);
        }
    }

    /**
     * 
     * MapListHandler:將ResultSet中所有的數據存成List。List中存放的是Map
     */

    public static void getMapListData() {
        Connection conn = getConnection();
        QueryRunner qr = new QueryRunner();
        try {
            List results = (List) qr.query(conn,
                    "SELECTid,username,gender FROM t_user",
                    new MapListHandler());
            for (int i = 0; i < results.size(); i++) {
                Map map = (Map) results.get(i);
                System.out.println("id=" + map.get("id") + " name="
                        + map.get("username") + " gender=" + map.get("gender"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(conn);
        }

    }

    /**
     * 
     * 新增和更新例子
     */

    public static void insertAndUpdateData() {
        Connection conn = getConnection();
        QueryRunner qr = new QueryRunner();
        try {
            // 創建一個數組來存要insert的數據
            Object[] insertParams = { "John Doe", "000000", "" };
            int inserts = qr
                    .update(conn,
                            "INSERT INTO t_user(username,password,gender) VALUES (?,?,?)",
                            insertParams);
            System.out.println("inserted " + inserts + " data");
            Object[] updateParams = { "111111", "John Doe" };
            int updates = qr.update(conn,
                    "UPDATE t_user SET password=? WHERE username=?",
                    updateParams);
            System.out.println("updated " + updates + " data");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(conn);
        }

    }

    /**
     * 
     * Unlike some other classes in DbUtils, this class(SqlNullCheckedResultSet)
     * is NOT thread-safe.
     */

    public static void findUseSqlNullCheckedResultSet() {
        Connection conn = getConnection();
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt
                    .executeQuery("SELECT id, username, gender FROM t_user");
            SqlNullCheckedResultSet wrapper = new SqlNullCheckedResultSet(rs);
            wrapper.setNullString("N/A"); // Set null string
            rs = ProxyFactory.instance().createResultSet(wrapper);
            while (rs.next()) {
                System.out.println("id=" + rs.getInt("id") + " username="
                        + rs.getString("username") + " gender="
                        + rs.getString("gender"));
            }
            rs.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(conn);
        }
    }

    /**** 數據庫連接*** */

    public static Connection getConnection() {
        Connection conn = null;
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://127.0.0.1/springapp?useUnicode=true&characterEncoding=gb2312";
        DbUtils.loadDriver(driver);
        try {
            conn = DriverManager.getConnection(url, "root", "root");
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return conn;
    }
View Code

 

 

Commons BeanUtils

Commons BeanUtils是針對Bean的一個工具集。由於Bean往往是有一堆get和set組成,所以BeanUtils也是在此基礎上進行一些包裝。

使用示例:一個比較常用的功能是Bean Copy,也就是copy bean的屬性。如果做分層架構開發的話就會用到,比如從PO(Persistent Object)拷貝數據到VO(Value Object)。

  1. 傳統方法如下:
TeacherFormteacherForm=(TeacherForm)form; //得到TeacherForm
Teacher teacher=new Teacher();//構造Teacher對象
//賦值
teacher.setName(teacherForm.getName());
teacher.setAge(teacherForm.getAge());
teacher.setGender(teacherForm.getGender());
teacher.setMajor(teacherForm.getMajor());
teacher.setDepartment(teacherForm.getDepartment());
//持久化Teacher對象到數據庫
HibernateDAO= ;
HibernateDAO.save(teacher);

 

使用BeanUtils后,代碼就大大改觀了,如下所示:

TeacherForm teacherForm=(TeacherForm)form; //得到TeacherForm
Teacher teacher=new Teacher();//構造Teacher對象
BeanUtils.copyProperties(teacher,teacherForm); //賦值
HibernateDAO.save(teacher); //持久化Teacher對象到數據庫

 

 

Commons CLI

說明:這是一個處理命令的工具。比如main方法輸入的string[]需要解析。你可以預先定義好參數的規則,然后就可以調用CLI來解析。
使用示例:

Options options = new Options();// create Options object
// add t option, option is the command parameter, false indicates that 
// this parameter is not required.
options.addOption(“t”, false, “display current time”);
options.addOption("c", true, "country code");
CommandLineParser parser = new PosixParser();
CommandLinecmd = parser.parse( options, args);
if(cmd.hasOption("t")) {
    // print the date and time
}
else {
    // print the date
}
// get c option value
String countryCode = cmd.getOptionValue("c");
if(countryCode == null) {
    // print default date
}
else {
    // print date for country specified by countryCode
}
View Code

 

 

Commons Codec

說明:這個工具是用來編碼和解碼的,包括Base64,URL,DES、SHA1、MD5、Soundx等等。

MD5

String str = "abc";

DigestUtils.md5Hex(str);

  

SHA1

String str = "abc";

DigestUtils.shaHex(str);

 

BASE64

//加密

String str= "abc"; // abc為要加密的字符串

byte[] b = Base64.encodeBase64(str.getBytes(), true);

System.out.println(new String(b));

 

//解密

String str = "YWJj"; // YWJj為要解密的字符串

byte[] b = Base64.decodeBase64(str.getBytes());

System.out.println(new String(b));

 

Commons Collections

說明:你可以把這個工具看成是java.util的擴展。

使用示例:舉一個簡單的例子

OrderedMap map = new LinkedMap();
map.put("FIVE", "5");
map.put("SIX", "6");
map.put("SEVEN", "7");
map.firstKey();  // returns "FIVE"
map.nextKey("FIVE");  // returns "SIX"
map.nextKey("SIX");  // returns "SEVEN"

 

Commons DBCP

說明:數據庫連接池,類似的還有common-pool和c3p0等,具體以后再總結

 

Commons HttpClient

詳情請參考:HttpClient學習整理

 

Commons IO

說明:可以看成是java.io的擴展

使用示例:

  1. 讀取Stream

a) 標准代碼:

InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
try {
   InputStreamReaderinR = new InputStreamReader( in );
   BufferedReaderbuf = new BufferedReader( inR );
   String line;
   while ( ( line = buf.readLine() ) != null ) {
     System.out.println( line );
   }
} finally {
   in.close();
}

b) 使用IOUtils
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
try {
   System.out.println( IOUtils.toString( in ) );
} finally {
   IOUtils.closeQuietly(in);
}

  1. 讀取文件

File file = new File("/commons/io/project.properties");
List lines = FileUtils.readLines(file, "UTF-8");

  1. 察看剩余空間

longfreeSpace = FileSystemUtils.freeSpace("C:/");

 

Commons JXPath

說明:那么JXpath就是基於Java對象的Xpath,也就是用Xpath對Java對象進行查詢。
使用示例:

Addressaddress=(Address)JXPathContext.newContext(vendor).getValue("locations[address/zipCode='90210']/address");
上述代碼等同於

Address address = null;
Collection locations = vendor.getLocations();
Iterator it = locations.iterator();
while (it.hasNext()){
    Location location = (Location)it.next();
    String zipCode = location.getAddress().getZipCode();
    if (zipCode.equals("90210")){
      address = location.getAddress();
      break;
    }
}

 

Commons Lang

說明:這個工具包可以看成是對java.lang的擴展。提供了諸如StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils等工具類。

Lang.*下有很多Utils類,提供了若干static方法供調用,涵蓋了字符串操作、字符操作、JVM交互操作、歸類、異常和位域校驗等等。

首先看看字符串處理類StringUtils

全部的靜態方法,StringUtils繼承自Object。屬於null safe操作。何謂null safe,就是遇到是null的string對象,也會quietly的把它處理掉,而不會有NullPointerException異常,如果有這個異常,那么就是該類的bug了~~

看看StringUtils的各種方法對比吧

比較一下isEmpty和isBlank這兩個方法。isEmpty在判斷” “這樣的字符串時返回的是false,而isBlank返回的是true。這就明顯了吧,empty只對null和””有效,而blank對” ”也有效~~

Clean方法和trim方法都封裝了String的trim方法,唯一的不同是clean將null處理為””,而trim將null處理為null。

以Strip開頭的一系列方法基本可以看做trim方法的擴展,但是更強大的是可以處理前導和后續的各種stripChars,不局限於空白符了。

Equal系列的方法加入了null的判斷,如果都是null那么也返回true。

IndexOf與String的indexOf類似,加入了null的判斷而已,且多了一個ordinalIndexOf方法,可以找到第n個字符串出現的位置。還有一個indexOfIgnoreCase可以不考慮大小寫的判斷位置匹配。實際代碼是調用了string的regionMatches方法,只不過在ignorecase參數上選擇了true。

Contains的實現是一樣的,只是加入了null的判斷。剩下的indexOfAny和containsAny方法都很不錯,完成了集合的匹配~~都包含一個字符數組的參數,可以檢測字符串中是否包含字符數組中的任意個元素,算法沒有特殊的地方,復雜度O(MN)吧~~相比較而言,contains系列的containsOnly和containsNone我倒是覺得更有用一些。

Substring系列的方法,除了substring封裝了string的substring完成了null safe的檢查外,還加入了left、right和mid方法。顧名思義,left可以得到最左邊的若干個字符作為字串,其實就是調用了str.substring(0, len);而right同樣是調用了str.substring(str.length() - len);另外還有一些比如substringBefore和substringAfter之類的,用法類似。substringBetween可以找到兩個字串中間的子串。

Split是值得說道的一個改動,原本大量封裝string的方法,split是個例外,大家知道,string的split方法用到的參數是一個正則式,雖然強大,但是有時候容易出錯。而且string並沒有提供簡化版本。StringUtils提供的split改變了這一狀況,開始使用完整的字符串作為參數,而不是regex。同時,對類似功能的jdk版本的StringTokenizer,在內部方法splitWorker中有段注釋:Direct code is quicker than StringTokenizer.也就是說,這個是更快的一個工具了~~

對於split的反向操作join,用到了一個lang.text包下的StrBuilder類。主要實現即將若干個object數組一個個的append到buffer中。然后最后toString就好。

Delete和remove可以用來刪除string中的內容,比如deleteSpaces可以除去字符串中的所有空白字符(" "t"r"n"b");remove更強大,可以removeStart(只匹配開頭)和removeEnd(只匹配結尾),當然remove可以刪掉字符串中的任意字串。

Replace,同理這里的replace不像string中的一樣是基於正則的,用起來更簡單。而且有replaceOnce和replaceEach等各種用法。還有一個輔助的overlay方法,可以直接替換~~

Chomp和chop我覺得是比較雞肋的一個功能了,去除字符串的最后一個字符或者尾部串,這功能很必要么?

Repeat將已有字符串復制n次。

Pad是一個很有意思的方法,可以將一個已有字符串擴展n個大小,並且填充特定的字符。比如StringUtils.rightPad("bat", 5, 'z') = "batzz"。Pad調用了string的concat方法。

Case conversion的操作就不用多講了,upper和lower都是一樣的。補充說的是,capitalize系列的方法真的很貼心。

補充一個容易讓人誤會的方法——countMatches,記錄一個字符串str中某串sub出現的次數。為什么容易誤會,“aaaa”中有多少“aa”呢?用該方法得到的答案是2~~~大家懂的

Is打頭的一系列方法都非常強大,可以判斷字符串是否符合某種格式,比如isAlpha判斷是否都是字母,isNumeric判斷是否都是數字等等等等。

Reverse這個功能出來后,最先想到的是當初筆試面試時候的一堆回文字符串翻轉之類的考試都要囧了。

Abbreviate方法我覺得是相當實用的一個方法封裝,我們在各種應用中都很常見的“一堆文字……”就是這個方法的最好應用。

Difference方法返回兩個字符串的不同處,可以說是返回第二個字符串的第一個不同的位置開始的子串。indexOfDifference返回不同處的位置。

getCommonPrefix這個方法也很好,可以找到一組字符串的公共前綴。當然只是調用了indexOfDifference這個方法。

接着就是ArrayUtils了

ArrayUtils是一個對數組進行特殊處理的類。當然jdk中的Arrays是有一些功能的,Array也提供了一些動態訪問java數組的方法,這里的ArrayUtils擴展提供了更多的功能。

第一個可以說的方法是toMap方法,該方法就是將一個二維數組轉換為一個HashMap。當然對輸入的參數要求比較嚴格,會拋出各種異常。NullToEmpty方法是一個防御性編程方法的代表,將null的數組直接變為一個空(長度為0)的數組。Subarray方法提供了基於拷貝的子數組生成方法。Reverse方法提供了一個數組翻轉的算法實現。indexOf方法是一個查找指定對象的線性數組查找方法。還提供了一系列裝箱拆箱方法(toPrimitive和toObject),就是將Integer之類的對象類型變成int,反之亦然。addAll方法提供了基於數組拷貝的數組合並,就是將數組1和數組2合並為一個新的數組返回。當然,add方法雖然只添加了一個元素,但是也是要數組拷貝的(數組的效率啊!!!)。同樣的原理,remove(刪除)方法也是基於數組拷貝的,以指定刪除元素為界,分別兩次拷貝它前后的子數組。

再來就是一些補充了

把一些看到的有意思的可能有用的接口方法提取出來。

RandomStringUtils類里有一個random方法,可以產生一個固定長度的隨機字符串。用到了java.util.Random。其中的注釋中提到了對Unicode中沒法處理的surrogate的處理方法。如果不幸隨機到那個位置(D800-DBFF, DC00-DFFF),那么算法中將進行count補充,即提供一次重新隨機的機會。

另外一個比較有趣的類是StopWatch,這是一個秒表類,通過start方法開始計時,通過split方法截斷每一次的分段計時,suspend方法可以暫停秒表,resume恢復計時。最后stop后可以通過getTime獲得總共計時。當然在split后的分段計時可以用getSplitTime獲取。技術實現上就是定義了幾個狀態,然后通過每次狀態的轉變和系統時間的差來表達計時效果。

 

Commons Math

說明:這個包提供的功能有些和Commons Lang重復了,但是這個包更專注於做數學工具,功能更強大。

Math 是一個輕量的,自包含的數學和統計組件,解決了許多非常通用但沒有及時出現在Java標准語言中的實踐問題.

  我們可以參考其主頁上的用戶指導(User Guide ).或者直接研究其API,發現在commons-math中有以下幾個包:

 1.org.apache.commons.math Common classes used throughout the commons-math library.

 2.org.apache.commons.math.analysis Implementations of common numerical analysis procedures, including root finding and function interpolation. 主要解決一些數學通常的分析方法,包括求方程的根,其中有對分算法,牛頓算法等等.以及函數的改寫.

 3.org.apache.commons.math.complex Complex number type and implementations of complex transcendental functions. 主要用來解決復數的計算.

 4.org.apache.commons.math.distribution Implementations of common discrete and continuous distributions.   主要用來解決連續分布和不連續分布的計算.

 5.org.apache.commons.math.fraction   Fraction number type and fraction number formatting.主要討論分數的格式和類型.

 6.org.apache.commons.math.linear    Linear algebra support. 線性代數中矩陣和行列式的算法.

 7.org.apache.commons.math.random   Random number and random data generators.隨機數算法

 8.org.apache.commons.math.special   Implementations of special functions such as Beta and Gamma.一些特別的函數算法.

 9.org.apache.commons.math.stat     Data storage, manipulation and summary routines.

 10.org.apache.commons.math.util    Convenience routines and common data structures used throughout the commons-math library.

 

Commons Net

 

說明:這個包還是很實用的,封裝了很多網絡協議。

 

1.    FTP
2.    NNTP
3.    SMTP
4.    POP3
5.    Telnet
6.    TFTP
7.    Finger
8.    Whois
9.    rexec/rcmd/rlogin
10.    Time (rdate) and Daytime
11.    Echo
12.    Discard
13.    NTP/SNTP

 

使用示例:

TelnetClient telnet = new TelnetClient();
telnet.connect( "192.168.1.99", 23 );
InputStream in = telnet.getInputStream();
PrintStream out = new PrintStream( telnet.getOutputStream() );
...
telnet.close();

 

Commons Validator

說明:用來幫助進行驗證的工具。比如驗證Email字符串,日期字符串等是否合法。
使用示例:

DateValidator validator = DateValidator.getInstance();// Get the Date validator
Date fooDate = validator.validate(fooString, "dd/MM/yyyy");// Validate/Convert the date
if (fooDate == null) {
     // error...not a valid date
     return;
}

Commons Virtual File System

說明:提供對各種資源的訪問接口。支持的資源類型包括

 

1.    CIFS 
2.    FTP 
3.    Local Files 
4.    HTTP and HTTPS 
5.    SFTP 
6.    Temporary Files 
7.    WebDAV 
8.    Zip, Jar and Tar (uncompressed, tgz or tbz2) 
9.    gzip and bzip2 
10.    res
11.    ram

 

這個包的功能很強大,極大的簡化了程序對資源的訪問。
使用示例:

  1. 從jar中讀取文件
    FileSystemManagerfsManager = VFS.getManager();// Locate the Jar file
    FileObjectjarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" );

    FileObject[] children = jarFile.getChildren();// List the children of the Jar file
    System.out.println( "Children of " + jarFile.getName().getURI() );
    for ( int i = 0; i <children.length; i++ )
    {
        System.out.println( children[ i ].getName().getBaseName() );
    }
  2. 從smb讀取文件
    StaticUserAuthenticatorauth = new StaticUserAuthenticator("username", "password", null);
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth); 
    FileObjectfo = VFS.getManager().resolveFile("smb://host/anyshare/dir", opts);

Commons Email

1、一個簡單的文本郵件

我們的第一個例子是利用你本地的郵件服務器向"John Doe"發送一個基本郵件信息。

import org.apache.commons.mail.SimpleEmail;

...

  SimpleEmail email = new SimpleEmail();

  email.setHostName("mail.myserver.com");

  email.addTo("jdoe@somewhere.org", "John Doe");

  email.setFrom("me@apache.org", "Me");

  email.setSubject("Test message");

  email.setMsg("This is a simple test of commons-email");

  email.send();

調用setHostName("mail.myserver.com")來設置發送信息的SMTP服務器地址。如果你不設置,將會使用系統屬性"mail.host"。

2、發送帶附件的郵件

為了向一個郵件添加附件,你需要使用MultiPartEmail這個類。這個類的工作方式和SimpleEmail類似,但是其重載了attach()方法使其可以向郵件添加附件。你可以通過附加或者內聯來添加無限數量的附件,這些附件將采用MIME編碼。

最簡單的方式是使用EmailAttachment類引用你得附件來添加附件。

下面的例子我們將創建一個圖片的附件。把圖片附加在郵件中並發送它。

import org.apache.commons.mail.*;

...

  // Create the attachment

  EmailAttachment attachment = new EmailAttachment();

  attachment.setPath("mypictures/john.jpg");

  attachment.setDisposition(EmailAttachment.ATTACHMENT);

  attachment.setDescription("Picture of John");

  attachment.setName("John");

  // Create the email message

  MultiPartEmail email = new MultiPartEmail();

  email.setHostName("mail.myserver.com");

  email.addTo("jdoe@somewhere.org", "John Doe");

  email.setFrom("me@apache.org", "Me");

  email.setSubject("The picture");

  email.setMsg("Here is the picture you wanted");

  // add the attachment

  email.attach(attachment);

  // send the email

  email.send();

你也可以使用EmailAttachment引用一個非本地的URL文件。當發送郵件時,URL文件會被自動下載下來附件在郵件中。

下面的例子演示如何把apache的徽標附件在郵件中發送給John 。

import org.apache.commons.mail.*;

...

  // Create the attachment

  EmailAttachment attachment = new EmailAttachment();

  attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));

  attachment.setDisposition(EmailAttachment.ATTACHMENT);

  attachment.setDescription("Apache logo");

  attachment.setName("Apache logo");

  // Create the email message

  MultiPartEmail email = new MultiPartEmail();

  email.setHostName("mail.myserver.com");

  email.addTo("jdoe@somewhere.org", "John Doe");

  email.setFrom("me@apache.org", "Me");

  email.setSubject("The logo");

  email.setMsg("Here is Apache's logo");

  

  // add the attachment

  email.attach(attachment);

  // send the email

  email.send();

 

3、發送HTML格式的郵件

發送HTML格式郵件要使用HtmlEmail類。這個類的工作方式很像使用附加方法設置html內容的MultiPartEmail類類似,如果接收者不支持HTML郵件將替換成普通的文本和內聯圖片。

在下面例子中,我們使用HTML格式內容和以俄國內聯圖像。

import org.apache.commons.mail.HtmlEmail;

...

  // Create the email message

  HtmlEmail email = new HtmlEmail();

  email.setHostName("mail.myserver.com");

  email.addTo("jdoe@somewhere.org", "John Doe");

  email.setFrom("me@apache.org", "Me");

  email.setSubject("Test email with inline image");

  // embed the image and get the content id

  URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");

  String cid = email.embed(url, "Apache logo");

  // set the html message

  email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");

  // set the alternative message

  email.setTextMsg("Your email client does not support HTML messages");

  // send the email

  email.send();

首先,注意,調用embed函數返回一個字符串。這個字符串是一個隨機的標識符用來引用一個圖像標簽中的圖像。下一步,在這個例子中我們沒有調用setMsg()函數。這個方法在HtmlEmail中仍然可用,但是如果你使用內聯圖像時就不應該使用,應該使用setHtmlMsg()函數和setTextMsg()函數。

4、調試

JavaMail API支持一個調試選項,如果你遇到了問題這個可能非常有用。你可以通過調用setDebug(true)來激活調試模式,調試信息將被輸出到標准輸出中。

5、驗證

如果SMTP服務器需要驗證,你可以在發送郵件前調用setAuthentication(userName,password)設置帳號和密碼。這個將會創建一個DefaultAuthenticator實例,JavaMail API在發送郵件時會使用它。你的服務器必須支持RFC2554標准。

 

參考:

http://zhoualine.iteye.com/blog/1770014


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM