欢迎访问宙启技术站
智能推送

Java常用函数大集合

发布时间:2023-06-01 00:42:18

Java是一种计算机编程语言,广泛应用于互联网和企业级开发中。其语法简单易懂,功能强大,可以实现各种各样的功能和需求。本文主要介绍一些Java常用函数,分为以下几个方面:

1.字符串操作相关

1.1 字符串转整型

使用Integer.parseInt()函数可以将字符串转为整型数。示例代码如下:

String str = "123";

int num = Integer.parseInt(str);

1.2 字符串拼接

使用字符串拼接符“+”可以将多个字符串拼接为一个。示例代码如下:

String str1 = "hello";

String str2 = "world";

String str3 = str1 + str2;

1.3 字符串分割

使用String.split()函数可以将字符串按照指定的分隔符进行分割,返回一个字符串数组。示例代码如下:

String str = "a,b,c";

String[] arr = str.split(",");

1.4 字符串截取

使用String.substring()函数可以截取字符串的指定部分。示例代码如下:

String str = "hello world";

String subStr = str.substring(0, 5);

1.5 字符串替换

使用String.replace()函数可以将字符串中指定的字符或字符串进行替换。示例代码如下:

String str = "hello world";

String newStr = str.replace("world", "java");

2.日期时间操作相关

2.1 获取当前时间

使用java.util.Date()函数可以获取当前的日期和时间。示例代码如下:

Date date = new Date();

2.2 格式化时间

使用SimpleDateFormat()函数可以格式化输出时间。示例代码如下:

Date date = new Date();

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dateStr = dateFormat.format(date);

2.3 时间计算

使用Calendar类进行时间计算。示例代码如下:

Calendar calendar = Calendar.getInstance();

calendar.setTime(new Date());

calendar.add(Calendar.DAY_OF_MONTH, 1);

Date tomorrow = calendar.getTime();

3.文件操作相关

3.1 文件读取

使用FileInputStream()函数可以读取文件内容。示例代码如下:

File file = new File("test.txt");

FileInputStream fis = new FileInputStream(file);

byte[] bytes = new byte[fis.available()];

fis.read(bytes);

String content = new String(bytes);

3.2 文件写入

使用FileOutputStream()函数可以向文件中写入内容。示例代码如下:

File file = new File("test.txt");

FileOutputStream fos = new FileOutputStream(file);

String content = "hello world";

byte[] bytes = content.getBytes();

fos.write(bytes);

3.3 文件复制

使用FileInputStream和FileOutputStream可以实现文件复制。示例代码如下:

File srcFile = new File("src.txt");

File destFile = new File("dest.txt");

FileInputStream fis = new FileInputStream(srcFile);

FileOutputStream fos = new FileOutputStream(destFile);

byte[] bytes = new byte[fis.available()];

fis.read(bytes);

fos.write(bytes);

4.集合操作相关

4.1 列表遍历

使用for循环或foreach语句可以遍历List列表。示例代码如下:

List<String> list = new ArrayList<>();

list.add("apple");

list.add("orange");

for (String str : list) {

    System.out.println(str);

}

4.2 列表排序

使用Collections.sort()函数可以对List列表进行排序。示例代码如下:

List<Integer> list = new ArrayList<>();

list.add(3);

list.add(1);

list.add(2);

Collections.sort(list);

4.3 列表去重

使用Set集合可以实现List列表去重。示例代码如下:

List<Integer> list = new ArrayList<>();

list.add(1);

list.add(2);

list.add(2);

list.add(3);

Set<Integer> set = new HashSet<>(list);

list = new ArrayList<>(set);

5.网络操作相关

5.1 发送HTTP请求

使用URLConnection可以发送HTTP请求。示例代码如下:

URL url = new URL("https://www.baidu.com");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");

conn.connect();

InputStream is = conn.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(is));

String line;

StringBuilder sb = new StringBuilder();

while ((line = reader.readLine()) != null) {

    sb.append(line);

}

String result = sb.toString();

5.2 发送邮件

使用JavaMail可以发送邮件。示例代码如下:

Properties props = new Properties();

props.put("mail.transport.protocol", "smtp");

props.put("mail.smtp.host", "smtp.qq.com");

props.put("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(props, new Authenticator() {

    protected PasswordAuthentication getPasswordAuthentication() {

        return new PasswordAuthentication("myusername@qq.com", "mypassword");

    }

});

try {

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress("myusername@qq.com"));

    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("target@qq.com"));

    message.setSubject("Test Email");

    message.setText("This is a test email.");

    Transport.send(message);

} catch (MessagingException e) {

    throw new RuntimeException(e);

}

6.其他常用函数

6.1 随机数生成

使用Random可以生成随机数。示例代码如下:

Random random = new Random();

int num = random.nextInt(100);

6.2 正则表达式匹配

使用Pattern和Matcher可以实现正则表达式匹配。示例代码如下:

String str = "hello123world";

Pattern pattern = Pattern.compile("\\d+");

Matcher matcher = pattern.matcher(str);

if (matcher.find()) {

    System.out.println(matcher.group());

}

6.3 异常处理

使用try-catch语句可以处理异常。示例代码如下:

try {

    // Some code that may throw an exception

} catch (Exception e) {

    e.printStackTrace();

} finally {

    // Code that always runs, regardless of whether an exception was thrown

}

以上就是Java常用函数的介绍,其中涵盖了各个方面的操作。可以根据实际需求选择使用。