Apache Commons Lang3 和 Commons Net 详解

目录

1. Apache Commons Lang3

1.1 什么是 Apache Commons Lang3?

1.2 主要功能

1.3 示例代码

2. Commons Net

2.1 什么是 Commons Net?

2.2 主要功能

2.3 示例代码

3. 总结

3.1 Apache Commons Lang3

3.2 Commons Net

3.3 使用建议

4. 参考资料


前言

        在 Java 开发中,Apache Commons 项目提供了许多实用的工具库,帮助开发者更高效地完成日常开发任务。本文将深入解析 Apache Commons Lang3Commons Net 这两个库的作用、技术细节以及实际应用,并通过示例代码演示它们的使用方法。


1. Apache Commons Lang3

1.1 什么是 Apache Commons Lang3?

Apache Commons Lang3 是 Apache Commons 项目中的一个工具库,提供了许多与 Java 核心类库相关的扩展功能,例如字符串处理、日期操作、对象工具等。它是 Java 开发中常用的工具库之一。

1.2 主要功能

  • 字符串处理:提供了丰富的字符串操作方法,如 StringUtils
  • 对象工具:提供了对象操作的工具类,如 ObjectUtils
  • 日期操作:提供了日期格式化和解析的工具类,如 DateUtils
  • 随机数生成:提供了随机数生成工具类,如 RandomUtils
  • 异常处理:提供了异常处理工具类,如 ExceptionUtils

1.3 示例代码

以下是一些常用的 StringUtilsDateUtils 示例:

字符串处理:

import org.apache.commons.lang3.StringUtils;

public class StringUtilsExample {
    public static void main(String[] args) {
        // 判断字符串是否为空
        boolean isEmpty = StringUtils.isEmpty(""); // true
        boolean isBlank = StringUtils.isBlank("  "); // true

        // 字符串截取
        String substring = StringUtils.substring("Hello World", 6); // "World"

        // 字符串拼接
        String join = StringUtils.join(new String[]{"Hello", "World"}, ", "); // "Hello, World"

        System.out.println("isEmpty: " + isEmpty);
        System.out.println("isBlank: " + isBlank);
        System.out.println("substring: " + substring);
        System.out.println("join: " + join);
    }
}

日期操作:

import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.util.Date;

public class DateUtilsExample {
    public static void main(String[] args) throws ParseException {
        // 解析日期
        Date date = DateUtils.parseDate("2023-10-15", "yyyy-MM-dd");

        // 添加天数
        Date newDate = DateUtils.addDays(date, 10);

        // 判断是否为同一天
        boolean isSameDay = DateUtils.isSameDay(date, newDate); // false

        System.out.println("date: " + date);
        System.out.println("newDate: " + newDate);
        System.out.println("isSameDay: " + isSameDay);
    }
}

NumberUtils

import org.apache.commons.lang3.math.NumberUtils;

public class NumberUtilsExample {
    public static void main(String[] args) {
        // 判断字符串是否为数字
        System.out.println(NumberUtils.isCreatable("123")); // true
        System.out.println(NumberUtils.isCreatable("12.3")); // true
        System.out.println(NumberUtils.isCreatable("abc")); // false

        // 获取最大值
        int max = NumberUtils.max(1, 2, 3);
        System.out.println("Max: " + max); // 3

        // 转换字符串为数字
        int number = NumberUtils.toInt("123", 0);
        System.out.println("Number: " + number); // 123
    }
}

ObjectUtils

import org.apache.commons.lang3.ObjectUtils;

public class ObjectUtilsExample {
    public static void main(String[] args) {
        // 获取非空对象
        String result = ObjectUtils.firstNonNull(null, "default", "fallback");
        System.out.println(result); // "default"

        // 比较对象
        int comparison = ObjectUtils.compare("a", "b");
        System.out.println(comparison); // -1

        // 克隆对象
        MyObject original = new MyObject("data");
        MyObject clone = ObjectUtils.clone(original);
        System.out.println(clone.getData()); // "data"
    }
}

class MyObject implements Cloneable {
    private String data;

    public MyObject(String data) {
        this.data = data;
    }

    public String getData() {
        return data;
    }

    @Override
    protected MyObject clone() {
        return new MyObject(this.data);
    }
}

2. Commons Net

2.1 什么是 Commons Net?

Commons Net 是 Apache Commons 项目中的一个网络工具库,提供了许多与网络协议相关的实现,例如 FTP、SMTP、POP3 等。它简化了网络编程的复杂性,帮助开发者快速实现网络功能。

2.2 主要功能

  • FTP 客户端:提供了 FTP 客户端的实现,支持文件上传、下载等操作。
  • SMTP 客户端:提供了 SMTP 客户端的实现,支持邮件发送。
  • POP3 客户端:提供了 POP3 客户端的实现,支持邮件接收。
  • Telnet 客户端:提供了 Telnet 客户端的实现,支持远程登录。

2.3 示例代码

以下是使用 FTPClient 进行文件上传和下载的示例:

FTP 文件上传:

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FtpUploadExample {
    public static void main(String[] args) {
        FTPClient ftpClient = new FTPClient();
        try {
            // 连接 FTP 服务器
            ftpClient.connect("ftp.example.com", 21);
            ftpClient.login("username", "password");

            // 设置文件类型为二进制
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            // 上传文件
            File file = new File("local-file.txt");
            FileInputStream inputStream = new FileInputStream(file);
            boolean success = ftpClient.storeFile("remote-file.txt", inputStream);
            inputStream.close();

            if (success) {
                System.out.println("文件上传成功!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

FTP 文件下载:

import org.apache.commons.net.ftp.FTPClient;

import java.io.FileOutputStream;
import java.io.IOException;

public class FtpDownloadExample {
    public static void main(String[] args) {
        FTPClient ftpClient = new FTPClient();
        try {
            // 连接 FTP 服务器
            ftpClient.connect("ftp.example.com", 21);
            ftpClient.login("username", "password");

            // 下载文件
            FileOutputStream outputStream = new FileOutputStream("local-file.txt");
            boolean success = ftpClient.retrieveFile("remote-file.txt", outputStream);
            outputStream.close();

            if (success) {
                System.out.println("文件下载成功!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3. 总结

3.1 Apache Commons Lang3

  • 优点:提供了丰富的工具类,简化了 Java 开发中的常见操作。
  • 适用场景:字符串处理、日期操作、对象工具等。

3.2 Commons Net

  • 优点:提供了多种网络协议的实现,简化了网络编程的复杂性。
  • 适用场景:FTP 文件传输、邮件发送与接收、远程登录等。

3.3 使用建议

  • Apache Commons Lang3:适合在需要处理字符串、日期、对象等场景中使用。
  • Commons Net:适合在需要实现网络功能(如 FTP、SMTP、POP3 等)的场景中使用。

4. 参考资料

commons-lang3.3.1.jar、Apache Commons包中的一个,包含了一些数据类型工具类,是java.lang.*的扩展。必须使用的jar包。为JRE5.0+的更好的版本所提供 Jar文件包含的类: META-INF/MANIFEST.MFMETA-INF/LICENSE.txtMETA-INF/NOTICE.txtorg.apache.commons.lang.ArrayUtils.class org.apache.commons.lang.BitField.class org.apache.commons.lang.BooleanUtils.class org.apache.commons.lang.CharEncoding.class org.apache.commons.lang.CharRange.class org.apache.commons.lang.CharSet.class org.apache.commons.lang.CharSetUtils.class org.apache.commons.lang.CharUtils.class org.apache.commons.lang.ClassUtils.class org.apache.commons.lang.Entities$ArrayEntityMap.class org.apache.commons.lang.Entities$BinaryEntityMap.class org.apache.commons.lang.Entities$EntityMap.class org.apache.commons.lang.Entities$HashEntityMap.class org.apache.commons.lang.Entities$LookupEntityMap.class org.apache.commons.lang.Entities$MapIntMap.class org.apache.commons.lang.Entities$PrimitiveEntityMap.class org.apache.commons.lang.Entities$TreeEntityMap.class org.apache.commons.lang.Entities.class org.apache.commons.lang.IllegalClassException.class org.apache.commons.lang.IncompleteArgumentException.class org.apache.commons.lang.IntHashMap$Entry.class org.apache.commons.lang.IntHashMap.class org.apache.commons.lang.LocaleUtils.class org.apache.commons.lang.NotImplementedException.class org.apache.commons.lang.NullArgumentException.class org.apache.commons.lang.NumberRange.class org.apache.commons.lang.NumberUtils.class org.apache.commons.lang.ObjectUtils$Null.class org.apache.commons.lang.ObjectUtils.class org.apache.commons.lang.RandomStringUtils.class org.apache.commons.lang.SerializationException.class org.apache.commons.lang.SerializationUtils.class org.apache.commons.lang.StringEscapeUtils.class org.apache.commons.lang.StringUtils.class org.apache.commons.lang.SystemUtils.class org.apache.commons.lang.UnhandledException.class org.apache.commons.lang.Validate.class org.apache.commons.lang.WordUtils.class org.apache.commons.lang.builder.CompareToBuilder.class org.apache.commons.lang.builder.EqualsBuilder.class org.apache.commons.lang.builder.HashCodeBuilder.class org.apache.commons.lang.builder.ReflectionToStringBuilder$1.class org.apache.commons.lang.builder.ReflectionToStringBuilder.class org.apache.commons.lang.builder.StandardToStringStyle.class org.apache.commons.lang.builder.ToStringBuilder.class org.apache.commons.lang.builder.ToStringStyle$DefaultToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$MultiLineToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$NoFieldNameToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$ShortPrefixToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$SimpleToStringStyle.class org.apache.commons.lang.builder.ToStringStyle.class org.apache.commons.lang.enum.Enum$Entry.class org.apache.commons.lang.enum.Enum.class org.apache.commons.lang.enum.EnumUtils.class org.apache.commons.lang.enum.ValuedEnum.class org.apache.commons.lang.enums.Enum$Entry.class org.apache.commons.lang.enums.Enum.class org.apache.commons.lang.enums.EnumUtils.class org.apache.commons.lang.enums.ValuedEnum.class org.apache.commons.lang.exception.ExceptionUtils.class org.apache.commons.lang.exception.Nestable.class org.apache.commons.lang.exception.NestableDelegate.class org.apache.commons.lang.exception.NestableError.class org.apache.commons.lang.exception.NestableException.class org.apache.commons.lang.exception.NestableRuntimeException.class org.apache.commons.lang.math.DoubleRange.class org.apache.commons.lang.math.FloatRange.class org.apache.commons.lang.math.Fraction.class org.apache.commons.lang.math.IntRange.class org.apache.commons.lang.math.JVMRandom.class org.apache.commons.lang.math.LongRange.class org.apache.commons.lang.math.NumberRange.class org.apache.commons.lang.math.NumberUtils.class org.apache.commons.lang.math.RandomUtils.class org.apache.commons.lang.math.Range.class org.apache.commons.lang.mutable.Mutable.class org.apache.commons.lang.mutable.MutableBoolean.class org.apache.commons.lang.mutable.MutableByte.class org.apache.commons.lang.mutable.MutableDouble.class org.apache.commons.lang.mutable.MutableFloat.class org.apache.commons.lang.mutable.MutableInt.class org.apache.commons.lang.mutable.MutableLong.class org.apache.commons.lang.mutable.MutableObject.class org.apache.commons.lang.mutable.MutableShort.class org.apache.commons.lang.text.CompositeFormat.class org.apache.commons.lang.text.StrBuilder$StrBuilderReader.class org.apache.commons.lang.text.StrBuilder$StrBuilderTokenizer.class org.apache.commons.lang.text.StrBuilder$StrBuilderWriter.class org.apache.commons.lang.text.StrBuilder.class org.apache.commons.lang.text.StrLookup$MapStrLookup.class org.apache.commons.lang.text.StrLookup.class org.apache.commons.lang.text.StrMatcher$CharMatcher.class org.apache.commons.lang.text.StrMatcher$CharSetMatcher.class org.apache.commons.lang.text.StrMatcher$NoMatcher.class org.apache.commons.lang.text.StrMatcher$StringMatcher.class org.apache.commons.lang.text.StrMatcher$TrimMatcher.class org.apache.commons.lang.text.StrMatcher.class org.apache.commons.lang.text.StrSubstitutor.class org.apache.commons.lang.text.StrTokenizer.class org.apache.commons.lang.time.DateFormatUtils.class org.apache.commons.lang.time.DateUtils$DateIterator.class org.apache.commons.lang.time.DateUtils.class org.apache.commons.lang.time.DurationFormatUtils$Token.class org.apache.commons.lang.time.DurationFormatUtils.class org.apache.commons.lang.time.FastDateFormat$CharacterLiteral.class org.apache.commons.lang.time.FastDateFormat$NumberRule.class org.apache.commons.lang.time.FastDateFormat$PaddedNumberField.class org.apache.commons.lang.time.FastDateFormat$Pair.class org.apache.commons.lang.time.FastDateFormat$Rule.class org.apache.commons.lang.time.FastDateFormat$StringLiteral.class org.apache.commons.lang.time.FastDateFormat$TextField.class org.apache.commons.lang.time.FastDateFormat$TimeZoneDisplayKey.class org.apache.commons.lang.time.FastDateFormat$TimeZoneNameRule.class org.apache.commons.lang.time.FastDateFormat$TimeZoneNumberRule.class org.apache.commons.lang.time.FastDateFormat$TwelveHourField.class org.apache.commons.lang.time.FastDateFormat$TwentyFourHourField.class org.apache.commons.lang.time.FastDateFormat$TwoDigitMonthField.class org.apache.commons.lang.time.FastDateFormat$TwoDigitNumberField.class org.apache.commons.lang.time.FastDateFormat$TwoDigitYearField.class org.apache.commons.lang.time.FastDateFormat$UnpaddedMonthField.class org.apache.commons.lang.time.FastDateFormat$UnpaddedNumberField.class org.apache.commons.lang.time.FastDateFormat.class org.apache.commons.lang.time.StopWatch.class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值