CodeGym /Java 博客 /随机的 /Java 中的 11 个 parse() 方法及其示例
John Squirrels
第 41 级
San Francisco

Java 中的 11 个 parse() 方法及其示例

已在 随机的 群组中发布
最一般意义上的解析是从一些数据中提取必要的信息,最常见的是文本数据。Java 中的解析是什么?许多 Java 类都具有parse()方法。通常parse()方法接收一些字符串作为输入,从中“提取”必要的信息并将其转换为调用类的对象。例如,它收到一个字符串并返回“隐藏”在该字符串中的日期。在这篇文章中,我们将看看parse()的 10 个有用的变体。

0.parseInt()

让我们从最流行的parse()方法之一开始,它不完全是parse(),而是parseInt()。Java parseInt()方法用于从特定字符串中获取原始数据类型。换句话说,它将字符串转换为数字。parseInt ()可以有一个或两个参数。这是parseInt()的语法:

static int parseInt(String s)
static int parseInt(String s, int radix)
其中s是表示带符号的十进制值和基数的数字系统基数的字符串。请记住,没有默认基值——您需要输入 2 到 36 范围内的一个值。这是一个示例。如何使用 ParseInt() 进行解析:

public class ParseInt0 {

       public static void main(String args[]){
           int x = Integer.parseInt("12");
           double c = Double.parseDouble("12");
           int b = Integer.parseInt("100",2);

           System.out.println(Integer.parseInt("12"));
           System.out.println(Double.parseDouble("12"));
           System.out.println(Integer.parseInt("100",2));
           System.out.println(Integer.parseInt("101", 8));
         
       }
   }
输出是:
12 12.0 4 65

1.句点parse()方法

Period是一个 Java 类,用于根据年、月和日对时间量进行建模,例如“3 年、5 个月和 2 天”。它有一个parse()方法来从文本中获取句点。这是period parse()的语法

public static Period parse(CharSequence text)
CharSequence 是一个接口,由字符串实现。因此,您可以在parse()方法中将字符串用作文本元素。确定字符串应该采用正确的格式以返回 Period 类的对象。这种格式是PnYnMnD。其中 Y 代表“年”,M 代表“月”,D 代表“日”。N 是对应于每个周期值的数字。
  • 该方法有一个参数——一个文本值。
  • Parse()返回一个 Period 值,其中字符串的值成为参数。
  • 作为例外,如果字符串值不符合句点的结构,句点 parse()可以返回 DateTimeParseException。
下面是一个在真实环境中 使用Period parse()的例子:

import java.time.Period;
public class ParseDemo1 {

   public static void main(String[] args)
   {
       //Here is the age String in format to  parse
       String age = "P17Y9M5D";

       // Converting strings into period value
       // using parse() method
       Period p = Period.parse(age);
       System.out.println("the age is: ");
       System.out.println(p.getYears() + " Years\n"
                          + p.getMonths() + " Months\n"
                          + p.getDays() + " Days\n");
   }
}
	} 
} 
输出是:
年龄是:17岁9个月5天

2.SimpleDateFormatParse()方法

SimpleDateFormat是一个用于以区域设置敏感方式格式化和解析日期的类。SimpleDateFormat parse()方法将字符串分解为日期标记并返回相应格式的数据值。该方法从开发人员定义的索引处开始解析字符串。这是SimpleDateFormat parse()的语法:

public Date parse(String the_text, ParsePosition position)
该方法有两个参数:
  • Position:起始索引处的数据,始终为 ParsePosition 对象类型。
  • the_text:定义了该方法要解析的字符串,是一个String类型的值。
您可以在没有位置声明的情况下使用此方法。在这种情况下,数据从零索引开始。 SimpleDateFormat parse()返回日期或空值(以防由于错误而未处理字符串)。这是SimpleDateFormat parse()实现的示例:

// Parsing strings into the Date format with two different patterns import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ParseDemo2 {
   public static void main(String[] args) throws ParseException {
       SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("MM/dd/yyyy");
       SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("dd/MM/yyyy");
       //simpleDateFormat1.setLenient(false);
       Date date1 = simpleDateFormat1.parse("010/14/2020");
       System.out.println(date1);
       Date date2 = simpleDateFormat2.parse("14/10/2020");
       System.out.println(date2);
       ParsePosition p1 = new ParsePosition(18);
       ParsePosition p2 = new ParsePosition(19);
       ParsePosition p3 = new ParsePosition(5);

       String myString = "here is the date: 14/010/2020";
       Date date3 = simpleDateFormat2.parse(myString,p1);
       Date date4 = simpleDateFormat2.parse(myString,p2);
       Date date5 = simpleDateFormat2.parse(myString,p3);

       System.out.println(date3);
       System.out.println(date4);
       System.out.println(date5);
   }
}
输出是:
EEST 2020 年 10 月 14 日星期三 00:00:00 EEST 2020 年 10 月 14 日星期三 00:00:00 EEST 2020 年 10 月 14 日星期三 00:00:00 2020 年 EEST 10 月 4 日星期日 00:00:00 null
最后一个为空,因为没有从第 5 个位置开始的日期模式。顺便说一下,如果您尝试解析没有位置的 date5,例如Date date5 = simpleDateFormat2.parse(myString),您将得到一个异常:
线程“main”中的异常 java.text.ParseException:无法解析的日期:“这里是日期:14/010/2020”,位于 ParseDemo2.main 的 java.base/java.text.DateFormat.parse(DateFormat.java:396) (ParseDemo2.java:22)

3. LocalDate 的 parse() 方法

LocalDate是Java 8中出现的一个类,用来表示年-月-日等日期(也可以访问day-of-year、day-of-week和week-of-year)。LocalDate 不代表时间或时区。 LocalDate parse()方法有两个变体。它们都有助于将字符串转换为新的 Java 8 日期 API — java.time.LocalDate

解析(CharSequence 文本、DateTimeFormatter、格式化程序)

此方法使用特定的格式化程序解析字符串以获得 LocalDate 的实例。下面是该方法的语法:

public static LocalTime parse(CharSequence text,
                              DateTimeFormatter formatter)
该方法有两个参数——将要解析的文本和开发人员将应用的格式化程序。作为返回值,该方法返回一个将被识别为本地白天时间的 LocalTime 对象。如果文本值无法通过解析,系统将抛出 DayTimeParseException。让我们看一个使用带有两个参数的LocalDate parse()的代码示例:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class ParserDemo3 {

   public static void main(String[]args) {

       DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
       String date = "14/10/2020";
       LocalDate localDate = LocalDate.parse(date, formatter);
       System.out.println("parsed local date: " + localDate);
       System.out.println("formatted local date: " + formatter.format(localDate));
   }
}
输出是:
解析的本地日期:2020-10-14 格式化的本地日期:14/10/2020
带有一个参数的LocalDate parse()方法具有以下语法:

public static LocalTime parse(CharSequence text)
此方法不需要指定格式化程序。开发人员在括号中输入字符串值后,系统将自动使用 DateTimeFormatter.ISO_LOCAL_DATE。该方法只有一个参数——一个 CharSequence 文本。您可以在此处使用字符串值。确保它不为 null 并尊重格式化程序的结构。如果无法解析字符串,开发人员会收到 DateTimeExceptionAlert。这是LocalDate parse()应用程序的示例:

import java.time.*;
public class ParseDemo3 {
       public static void main(String[] args)
       {
           // let’s make a new LocalDate object
           LocalDate localDate = LocalDate.parse("2020-10-14");
           System.out.println("LocalDate : " + localDate);
       }
   }
输出是:
本地日期:2020-10-14

4. LocalDateTime parse() 方法

LocalDateTime一个日期时间对象,表示日期时间通常被视为年月日时分秒。开发人员还可以使用其他日期和时间字段(一年中的某一天、星期几和一年中的一周)。这个类是不可变的。时间以纳秒精度表示。例如,您可以将值“2020 年 11 月 17 日 13:30.30.123456789”存储在 LocalDateTime 中。此类与表示时区无关。它是一个标准的日期表示加上本地时间。 LocalDateTime parse()方法以两种变体表示:
  • static LocalDateTime parse(CharSequence text)从文本字符串(例如 2007-12-03T10:15:30)返回 LocalDateTime 的实例。
  • static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)使用特定格式化程序从文本字符串返回 LocalDateTime 的实例。
这是LocalDateTime parse()方法的示例:

import java.time.*;
public class ParseDemo11 {
       public static void main(String[] args) {
           LocalDateTime localDateTime = LocalDateTime.parse("2020-11-17T19:34:50.63");
           System.out.println("LocalDateTime is: " + localDateTime);
       }
   }
输出是:
LocalDateTime 是:2020-11-17T19:34:50.630

5. ZonedDateTime parse() 方法

ZonedDateTime类表示带有时区的日期时间。这个类是不可变的。它存储日期和时间字段,精度为纳秒,时区,时区偏移量用于处理不明确的本地日期时间。因此,如果您需要保留诸如“欧洲/巴黎时区 2020 年 10 月 14 日 17:50.30.123456789 +02:00”之类的值,您可以使用 ZonedDateTime。该类通常用于操作基于本地时间的数据。 ZondeDateTime parse()是一个解析器,它将字符串分解为 ISO-8061 系统中的标记。这是解析后将获得的值的示例:
2020-04-05T13:30:25+01:00 欧洲/罗马
每当需要高精度数据时都会使用它(毕竟,您获得的数据精确到纳秒级)。该类通常用于操作基于本地时间的数据。让我们看一下开发人员用来将字符串值转换为 ZonedDateTime 类 的ZonedDateTime parse()方法的一般语法。

public static ZonedDateTime parse(CharSequence text)
该方法使用的唯一参数是字符串文本。作为返回值,您将获得一个或一系列 ZonedDateTime 格式的对象。如果在解析过程中出现错误或无法解析,则该方法首先返回 DateTimeParseException。还有一个带有两个变量的parse()方法。

public static ZonedDateTime parse(CharSequence text, DateFormatter formatter)
此方法使用特定格式化程序从文本值获取 ZonedDateTime 的实例。默认使用带一个参数的格式化程序DateTimeFormatter.ISO_LOCAL_TIME的方法。让我们看一下 ZonedDateTime parse() 的用例:

// An example program that uses
// ZonedDateTime.parse() method
  
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class ParseDemo4 {
   public static void main(String[] args) {
       ZonedDateTime zonedDateTime = ZonedDateTime.parse("2020-10-15T10:15:30+01:00");
       System.out.println(zonedDateTime);

       DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
       String date = "2020-10-15T13:30:25+01:00";
       ZonedDateTime zoneDateTime1 = ZonedDateTime.parse(date, dateTimeFormatter);
       System.out.println(zoneDateTime1);
   }
}
输出是:
2020-10-15T10:15:30+01:00 2020-10-15T13:30:25+01:00

6. LocalTime parse() 方法

LocalTime类表示一个时间,通常被视为小时-分钟-秒。此类也是不可变的,例如 ZonedDateTime.Time 以纳秒精度表示。例如,值“13:45.30.123456789”可以存储在 LocalTime 中。有两种LocalTime parse()方法,具有一个和两个参数。让我们来看看两者:

public static LocalTime parse(CharSequence text)
您可以使用只有一个参数的LocalTime parse(),即您要解析的字符串。在这种情况下,默认使用格式化程序 DateTimeFormatter.ISO_LOCAL_TIME。

Method with two parameters has the next syntax: 
public static LocalTime parse(CharSequence text,
                              DateTimeFormatter formatter)
它使用特定的格式化程序从文本值中获取 LocalTime 的实例。这两种方法都以 hh/mm/ss 格式返回 LocalTime 值。注意 DateTimeParceException 警报。它们意味着字符串文本的格式与 LocalTime 对象的格式不对应。这是在生产中使用LocalTime parse()的示例:

import java.time.*;
import java.time.format.*;
public class ParseDemo5 {

       public static void main(String[] args)
       {

           LocalTime localTime
                   = LocalTime.parse("10:25:30");

           // return the output value
           System.out.println("LocalTime : "
                              + localTime);

           // create a formater
           DateTimeFormatter formatter
                   = DateTimeFormatter.ISO_LOCAL_TIME;

           LocalTime localTime1
                   = LocalTime.parse("12:30:50");
           // parse a string to get a LocalTime object in return

           LocalTime.parse("12:30:50",
               formatter);
           // print the output
           System.out.println("LocalTime : "
                              + localTime1);
       }
   }

7. MessageFormat Parse() 方法

MessageFormat扩展了 Format 类。Format 是一个抽象基类,用于格式化区域设置敏感数据(日期、消息和数字)。MessageFormat 获取一些对象并格式化它们。然后它将格式化的字符串插入到模式中适当的位置。如果给定索引开头,则MessageFormat parse()用于获取字符串值。下面是该方法的一般语法:

public Object[] parse(String source, ParsePosition position)
其中source是要解析的字符串,position是解析的起始索引。这是MessageFormat parse()方法工作的示例:

import java.text.MessageFormat;
import java.text.ParsePosition;

public class ParseDemo7 {
   public static void main(String[] args) {
    try {
           MessageFormat messageFormat = new MessageFormat("{1, number, #}, {0, number, #.#}, {2, number, #.##}");

           ParsePosition pos = new ParsePosition(3);
           Object[] hash = messageFormat.parse("12.101, 21.382, 35.121", pos);

           System.out.println("value after parsing: ");
           for (int i = 0; i < hash.length; i++)
               System.out.println(hash[i]);
       }
       catch (NullPointerException e) {
          System.out.println("\nNull");
          System.out.println("Exception thrown : " + e);
       } }
}

8.关卡parse()方法

当程序员使用 Logger 记录一条消息时,它会以特定的日志级别进行记录。有七个内置日志级别:
  • 严重
  • 警告
  • 信息
  • 配置
  • 美好的
  • 更精细
  • 最好的
还有其他级别 OFF 可用于关闭日志记录和 ALL 可用于启用所有消息的日志记录。日志级别由类java.util.logging.Level表示。级别类包含这七个级别中的每一个级别的常量。因此,您在将消息记录到 Logger 时使用这些常量之一,包括 All 和 OFF。所有这些级别也都初始化为一些整数。例如 FINE 被初始化为 500。Level parse()方法从文本值中解析出所需的信息并返回一个 Level 对象。下面是level parse()方法的语法:

public static Level parse(String name)
方法的参数是开发人员要解析的字符串的名称。它可以是关卡的名称、它的初始化名称或其他一些整数。作为回报,程序员会得到一个级别名称值,对应于初始字符串的名称值。如果参数包含无法解析的符号,系统将抛出 IllegalArgumentException。如果字符串不包含任何值,开发人员将收到 NullPointerException。这是一段代码,显示了Level parse()的实现。

import java.util.logging.Level;
public class ParseDemo6 {

   public static void main(String[] args)
   {
       Level level = Level.parse("500");
       System.out.println("Level = " + level.toString());

       Level level1 = Level.parse("FINE");
       System.out.println("Level = " + level1.toString());

       Level level2 = level.parse ("OFF");
       System.out.println(level2.toString());
   }
}
输出是:
级别 = 精细级别 = 精细关闭

9.即时parse()方法

Instant类模拟时间线上的单个瞬时点。您可以使用它在您的应用程序中记录事件时间戳。 Instant parse()从文本值中获取 Instant 值。该字符串稍后将存储为 UTC 时区值。系统使用 DateTimeFormatter.ISO_INSTANT 如 2020-10-14T11:28:15.00Z。这是Instant parse()方法的语法:

public static Instant parse(CharSequence text)
要解析字符串并获得即时信息,开发人员需要确保该字符串包含一些文本。如果它为 null,您将得到一个 DateTimeException。下面是在 Java 中 使用Instant parse的示例:

import java.time.Instant;

public class ParseDemo8 {
       public static void main(String[] args) {

           Instant instant = Instant.parse("2020-10-14T10:37:30.00Z");
           System.out.println(instant);
       }
   }
输出是:
2020-10-14T10:37:30Z

10. NumberFormat parse() 方法

java.text.NumberFormat类用于格式化数字。NumberFormat parse()是此类的默认方法。NumberFormat 类的parse ()方法将字符串转换为数字。开发人员使用它将字符串分解为其组件编号。解析从字符串的开头开始。如果在调用parse()方法之前调用setParseIntegerOnly(true),如下例所示,那么只会转换数字的整数部分。下面是NumberFormat parse()的语法:

public Number parse(String str)
作为参数,该函数接受字符串。解析的返回值为数值。如果无法解析字符串开头,您将收到 ParseException 警告。要查看NumberFormat parse()方法的应用,请看下面的示例:

import java.text.NumberFormat;
import java.text.ParseException;

public class ParseDemo9 {

       public static void main(String[] args) throws ParseException {
           NumberFormat numberFormat = NumberFormat.getInstance();
           System.out.println(numberFormat.parse("3,141592"));
           numberFormat.setParseIntegerOnly(true);
           System.out.println(numberFormat.parse("3,141592"));
       }
   }
输出是:
3.141592 3

结论

开发人员可以使用多种解析方法将字符串转换为各种数据类型。尽管记住它们似乎很乏味,但如此多样的命令为开发人员提供了很大的灵活性和精确性。一定要练习使用数据解析,以确保您记住了语法并且不会忘记哪些参数对于每个方法都是必不可少的。
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION