关于libphonenumber兼容JRE 1.7.0_79的Jar及号码格式化咨询
CountryCode-AreaCode-NationalNumber & Where to Get a JRE 1.7.0_79 Compatible JAR? Absolutely! The libphonenumber library is tailor-made for this kind of phone number manipulation—let me walk you through how to implement your formatting requirement, plus how to grab a JAR that works with your older JRE version.
1. Implementing the Custom Number Format
libphonenumber doesn’t have this exact format built-in, but you can easily extract the components you need and assemble them into your desired structure. Here’s a step-by-step Java example:
Step 1: Initialize the core utility class
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Step 2: Parse the input number
Your example input includes a country code (33 for France), so we can use UNKNOWN_REGION for parsing. If you have numbers without explicit country codes, you’d pass the default region instead.
Phonenumber.PhoneNumber parsedNumber = null; try { parsedNumber = phoneUtil.parse("330660684937", PhoneNumberUtil.UNKNOWN_REGION); } catch (NumberParseException e) { // Handle invalid number errors here e.printStackTrace(); }
Step 3: Build your custom formatted string
Extract the country code, area code, and remaining national number, then assemble them. To make this work across multiple countries dynamically, use the library’s method to get the area code length for the parsed number:
if (parsedNumber != null) { int countryCode = parsedNumber.getCountryCode(); String fullNationalNumber = phoneUtil.getNationalNumber(parsedNumber).toString(); // Get area code length dynamically (works for all supported countries) int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(parsedNumber); String areaCode = ""; String remainingNationalNumber = fullNationalNumber; if (areaCodeLength > 0) { areaCode = fullNationalNumber.substring(0, areaCodeLength); remainingNationalNumber = fullNationalNumber.substring(areaCodeLength); } // Assemble the final format String formattedNumber = String.format("%d-%s-%s", countryCode, areaCode, remainingNationalNumber); // Output for your example: "33-06-60684937" }
2. Getting a JRE 1.7.0_79 Compatible JAR
libphonenumber dropped Java 7 support in versions after 8.12.56—this is the last release that works with JRE 1.7.0_79.
- If you use Maven, add this dependency to your
pom.xml:
<dependency> <groupId>com.googlecode.libphonenumber</groupId> <artifactId>libphonenumber</artifactId> <version>8.12.56</version> </dependency>
- For a standalone JAR, retrieve it from Maven Central by searching for the group ID
com.googlecode.libphonenumber, artifact IDlibphonenumber, and version8.12.56. This version explicitly targets Java 7 and will be fully compatible with your JRE.
内容的提问来源于stack exchange,提问作者Lara Noueir

