001/* 002 * Copyright 2002-2020 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.util; 018 019import java.io.ByteArrayOutputStream; 020import java.nio.charset.Charset; 021import java.util.ArrayDeque; 022import java.util.ArrayList; 023import java.util.Arrays; 024import java.util.Collection; 025import java.util.Collections; 026import java.util.Deque; 027import java.util.Enumeration; 028import java.util.Iterator; 029import java.util.LinkedHashSet; 030import java.util.List; 031import java.util.Locale; 032import java.util.Properties; 033import java.util.Set; 034import java.util.StringJoiner; 035import java.util.StringTokenizer; 036import java.util.TimeZone; 037 038import org.springframework.lang.Nullable; 039 040/** 041 * Miscellaneous {@link String} utility methods. 042 * 043 * <p>Mainly for internal use within the framework; consider 044 * <a href="https://commons.apache.org/proper/commons-lang/">Apache's Commons Lang</a> 045 * for a more comprehensive suite of {@code String} utilities. 046 * 047 * <p>This class delivers some simple functionality that should really be 048 * provided by the core Java {@link String} and {@link StringBuilder} 049 * classes. It also provides easy-to-use methods to convert between 050 * delimited strings, such as CSV strings, and collections and arrays. 051 * 052 * @author Rod Johnson 053 * @author Juergen Hoeller 054 * @author Keith Donald 055 * @author Rob Harrop 056 * @author Rick Evans 057 * @author Arjen Poutsma 058 * @author Sam Brannen 059 * @author Brian Clozel 060 * @since 16 April 2001 061 */ 062public abstract class StringUtils { 063 064 private static final String[] EMPTY_STRING_ARRAY = {}; 065 066 private static final String FOLDER_SEPARATOR = "/"; 067 068 private static final String WINDOWS_FOLDER_SEPARATOR = "\\"; 069 070 private static final String TOP_PATH = ".."; 071 072 private static final String CURRENT_PATH = "."; 073 074 private static final char EXTENSION_SEPARATOR = '.'; 075 076 077 //--------------------------------------------------------------------- 078 // General convenience methods for working with Strings 079 //--------------------------------------------------------------------- 080 081 /** 082 * Check whether the given object (possibly a {@code String}) is empty. 083 * This is effectively a shortcut for {@code !hasLength(String)}. 084 * <p>This method accepts any Object as an argument, comparing it to 085 * {@code null} and the empty String. As a consequence, this method 086 * will never return {@code true} for a non-null non-String object. 087 * <p>The Object signature is useful for general attribute handling code 088 * that commonly deals with Strings but generally has to iterate over 089 * Objects since attributes may e.g. be primitive value objects as well. 090 * <p><b>Note: If the object is typed to {@code String} upfront, prefer 091 * {@link #hasLength(String)} or {@link #hasText(String)} instead.</b> 092 * @param str the candidate object (possibly a {@code String}) 093 * @since 3.2.1 094 * @see #hasLength(String) 095 * @see #hasText(String) 096 */ 097 public static boolean isEmpty(@Nullable Object str) { 098 return (str == null || "".equals(str)); 099 } 100 101 /** 102 * Check that the given {@code CharSequence} is neither {@code null} nor 103 * of length 0. 104 * <p>Note: this method returns {@code true} for a {@code CharSequence} 105 * that purely consists of whitespace. 106 * <p><pre class="code"> 107 * StringUtils.hasLength(null) = false 108 * StringUtils.hasLength("") = false 109 * StringUtils.hasLength(" ") = true 110 * StringUtils.hasLength("Hello") = true 111 * </pre> 112 * @param str the {@code CharSequence} to check (may be {@code null}) 113 * @return {@code true} if the {@code CharSequence} is not {@code null} and has length 114 * @see #hasLength(String) 115 * @see #hasText(CharSequence) 116 */ 117 public static boolean hasLength(@Nullable CharSequence str) { 118 return (str != null && str.length() > 0); 119 } 120 121 /** 122 * Check that the given {@code String} is neither {@code null} nor of length 0. 123 * <p>Note: this method returns {@code true} for a {@code String} that 124 * purely consists of whitespace. 125 * @param str the {@code String} to check (may be {@code null}) 126 * @return {@code true} if the {@code String} is not {@code null} and has length 127 * @see #hasLength(CharSequence) 128 * @see #hasText(String) 129 */ 130 public static boolean hasLength(@Nullable String str) { 131 return (str != null && !str.isEmpty()); 132 } 133 134 /** 135 * Check whether the given {@code CharSequence} contains actual <em>text</em>. 136 * <p>More specifically, this method returns {@code true} if the 137 * {@code CharSequence} is not {@code null}, its length is greater than 138 * 0, and it contains at least one non-whitespace character. 139 * <p><pre class="code"> 140 * StringUtils.hasText(null) = false 141 * StringUtils.hasText("") = false 142 * StringUtils.hasText(" ") = false 143 * StringUtils.hasText("12345") = true 144 * StringUtils.hasText(" 12345 ") = true 145 * </pre> 146 * @param str the {@code CharSequence} to check (may be {@code null}) 147 * @return {@code true} if the {@code CharSequence} is not {@code null}, 148 * its length is greater than 0, and it does not contain whitespace only 149 * @see #hasText(String) 150 * @see #hasLength(CharSequence) 151 * @see Character#isWhitespace 152 */ 153 public static boolean hasText(@Nullable CharSequence str) { 154 return (str != null && str.length() > 0 && containsText(str)); 155 } 156 157 /** 158 * Check whether the given {@code String} contains actual <em>text</em>. 159 * <p>More specifically, this method returns {@code true} if the 160 * {@code String} is not {@code null}, its length is greater than 0, 161 * and it contains at least one non-whitespace character. 162 * @param str the {@code String} to check (may be {@code null}) 163 * @return {@code true} if the {@code String} is not {@code null}, its 164 * length is greater than 0, and it does not contain whitespace only 165 * @see #hasText(CharSequence) 166 * @see #hasLength(String) 167 * @see Character#isWhitespace 168 */ 169 public static boolean hasText(@Nullable String str) { 170 return (str != null && !str.isEmpty() && containsText(str)); 171 } 172 173 private static boolean containsText(CharSequence str) { 174 int strLen = str.length(); 175 for (int i = 0; i < strLen; i++) { 176 if (!Character.isWhitespace(str.charAt(i))) { 177 return true; 178 } 179 } 180 return false; 181 } 182 183 /** 184 * Check whether the given {@code CharSequence} contains any whitespace characters. 185 * @param str the {@code CharSequence} to check (may be {@code null}) 186 * @return {@code true} if the {@code CharSequence} is not empty and 187 * contains at least 1 whitespace character 188 * @see Character#isWhitespace 189 */ 190 public static boolean containsWhitespace(@Nullable CharSequence str) { 191 if (!hasLength(str)) { 192 return false; 193 } 194 195 int strLen = str.length(); 196 for (int i = 0; i < strLen; i++) { 197 if (Character.isWhitespace(str.charAt(i))) { 198 return true; 199 } 200 } 201 return false; 202 } 203 204 /** 205 * Check whether the given {@code String} contains any whitespace characters. 206 * @param str the {@code String} to check (may be {@code null}) 207 * @return {@code true} if the {@code String} is not empty and 208 * contains at least 1 whitespace character 209 * @see #containsWhitespace(CharSequence) 210 */ 211 public static boolean containsWhitespace(@Nullable String str) { 212 return containsWhitespace((CharSequence) str); 213 } 214 215 /** 216 * Trim leading and trailing whitespace from the given {@code String}. 217 * @param str the {@code String} to check 218 * @return the trimmed {@code String} 219 * @see java.lang.Character#isWhitespace 220 */ 221 public static String trimWhitespace(String str) { 222 if (!hasLength(str)) { 223 return str; 224 } 225 226 int beginIndex = 0; 227 int endIndex = str.length() - 1; 228 229 while (beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex))) { 230 beginIndex++; 231 } 232 233 while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) { 234 endIndex--; 235 } 236 237 return str.substring(beginIndex, endIndex + 1); 238 } 239 240 /** 241 * Trim <i>all</i> whitespace from the given {@code String}: 242 * leading, trailing, and in between characters. 243 * @param str the {@code String} to check 244 * @return the trimmed {@code String} 245 * @see java.lang.Character#isWhitespace 246 */ 247 public static String trimAllWhitespace(String str) { 248 if (!hasLength(str)) { 249 return str; 250 } 251 252 int len = str.length(); 253 StringBuilder sb = new StringBuilder(str.length()); 254 for (int i = 0; i < len; i++) { 255 char c = str.charAt(i); 256 if (!Character.isWhitespace(c)) { 257 sb.append(c); 258 } 259 } 260 return sb.toString(); 261 } 262 263 /** 264 * Trim leading whitespace from the given {@code String}. 265 * @param str the {@code String} to check 266 * @return the trimmed {@code String} 267 * @see java.lang.Character#isWhitespace 268 */ 269 public static String trimLeadingWhitespace(String str) { 270 if (!hasLength(str)) { 271 return str; 272 } 273 274 StringBuilder sb = new StringBuilder(str); 275 while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { 276 sb.deleteCharAt(0); 277 } 278 return sb.toString(); 279 } 280 281 /** 282 * Trim trailing whitespace from the given {@code String}. 283 * @param str the {@code String} to check 284 * @return the trimmed {@code String} 285 * @see java.lang.Character#isWhitespace 286 */ 287 public static String trimTrailingWhitespace(String str) { 288 if (!hasLength(str)) { 289 return str; 290 } 291 292 StringBuilder sb = new StringBuilder(str); 293 while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { 294 sb.deleteCharAt(sb.length() - 1); 295 } 296 return sb.toString(); 297 } 298 299 /** 300 * Trim all occurrences of the supplied leading character from the given {@code String}. 301 * @param str the {@code String} to check 302 * @param leadingCharacter the leading character to be trimmed 303 * @return the trimmed {@code String} 304 */ 305 public static String trimLeadingCharacter(String str, char leadingCharacter) { 306 if (!hasLength(str)) { 307 return str; 308 } 309 310 StringBuilder sb = new StringBuilder(str); 311 while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) { 312 sb.deleteCharAt(0); 313 } 314 return sb.toString(); 315 } 316 317 /** 318 * Trim all occurrences of the supplied trailing character from the given {@code String}. 319 * @param str the {@code String} to check 320 * @param trailingCharacter the trailing character to be trimmed 321 * @return the trimmed {@code String} 322 */ 323 public static String trimTrailingCharacter(String str, char trailingCharacter) { 324 if (!hasLength(str)) { 325 return str; 326 } 327 328 StringBuilder sb = new StringBuilder(str); 329 while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) { 330 sb.deleteCharAt(sb.length() - 1); 331 } 332 return sb.toString(); 333 } 334 335 /** 336 * Test if the given {@code String} matches the given single character. 337 * @param str the {@code String} to check 338 * @param singleCharacter the character to compare to 339 * @since 5.2.9 340 */ 341 public static boolean matchesCharacter(@Nullable String str, char singleCharacter) { 342 return (str != null && str.length() == 1 && str.charAt(0) == singleCharacter); 343 } 344 345 /** 346 * Test if the given {@code String} starts with the specified prefix, 347 * ignoring upper/lower case. 348 * @param str the {@code String} to check 349 * @param prefix the prefix to look for 350 * @see java.lang.String#startsWith 351 */ 352 public static boolean startsWithIgnoreCase(@Nullable String str, @Nullable String prefix) { 353 return (str != null && prefix != null && str.length() >= prefix.length() && 354 str.regionMatches(true, 0, prefix, 0, prefix.length())); 355 } 356 357 /** 358 * Test if the given {@code String} ends with the specified suffix, 359 * ignoring upper/lower case. 360 * @param str the {@code String} to check 361 * @param suffix the suffix to look for 362 * @see java.lang.String#endsWith 363 */ 364 public static boolean endsWithIgnoreCase(@Nullable String str, @Nullable String suffix) { 365 return (str != null && suffix != null && str.length() >= suffix.length() && 366 str.regionMatches(true, str.length() - suffix.length(), suffix, 0, suffix.length())); 367 } 368 369 /** 370 * Test whether the given string matches the given substring 371 * at the given index. 372 * @param str the original string (or StringBuilder) 373 * @param index the index in the original string to start matching against 374 * @param substring the substring to match at the given index 375 */ 376 public static boolean substringMatch(CharSequence str, int index, CharSequence substring) { 377 if (index + substring.length() > str.length()) { 378 return false; 379 } 380 for (int i = 0; i < substring.length(); i++) { 381 if (str.charAt(index + i) != substring.charAt(i)) { 382 return false; 383 } 384 } 385 return true; 386 } 387 388 /** 389 * Count the occurrences of the substring {@code sub} in string {@code str}. 390 * @param str string to search in 391 * @param sub string to search for 392 */ 393 public static int countOccurrencesOf(String str, String sub) { 394 if (!hasLength(str) || !hasLength(sub)) { 395 return 0; 396 } 397 398 int count = 0; 399 int pos = 0; 400 int idx; 401 while ((idx = str.indexOf(sub, pos)) != -1) { 402 ++count; 403 pos = idx + sub.length(); 404 } 405 return count; 406 } 407 408 /** 409 * Replace all occurrences of a substring within a string with another string. 410 * @param inString {@code String} to examine 411 * @param oldPattern {@code String} to replace 412 * @param newPattern {@code String} to insert 413 * @return a {@code String} with the replacements 414 */ 415 public static String replace(String inString, String oldPattern, @Nullable String newPattern) { 416 if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) { 417 return inString; 418 } 419 int index = inString.indexOf(oldPattern); 420 if (index == -1) { 421 // no occurrence -> can return input as-is 422 return inString; 423 } 424 425 int capacity = inString.length(); 426 if (newPattern.length() > oldPattern.length()) { 427 capacity += 16; 428 } 429 StringBuilder sb = new StringBuilder(capacity); 430 431 int pos = 0; // our position in the old string 432 int patLen = oldPattern.length(); 433 while (index >= 0) { 434 sb.append(inString, pos, index); 435 sb.append(newPattern); 436 pos = index + patLen; 437 index = inString.indexOf(oldPattern, pos); 438 } 439 440 // append any characters to the right of a match 441 sb.append(inString, pos, inString.length()); 442 return sb.toString(); 443 } 444 445 /** 446 * Delete all occurrences of the given substring. 447 * @param inString the original {@code String} 448 * @param pattern the pattern to delete all occurrences of 449 * @return the resulting {@code String} 450 */ 451 public static String delete(String inString, String pattern) { 452 return replace(inString, pattern, ""); 453 } 454 455 /** 456 * Delete any character in a given {@code String}. 457 * @param inString the original {@code String} 458 * @param charsToDelete a set of characters to delete. 459 * E.g. "az\n" will delete 'a's, 'z's and new lines. 460 * @return the resulting {@code String} 461 */ 462 public static String deleteAny(String inString, @Nullable String charsToDelete) { 463 if (!hasLength(inString) || !hasLength(charsToDelete)) { 464 return inString; 465 } 466 467 int lastCharIndex = 0; 468 char[] result = new char[inString.length()]; 469 for (int i = 0; i < inString.length(); i++) { 470 char c = inString.charAt(i); 471 if (charsToDelete.indexOf(c) == -1) { 472 result[lastCharIndex++] = c; 473 } 474 } 475 if (lastCharIndex == inString.length()) { 476 return inString; 477 } 478 return new String(result, 0, lastCharIndex); 479 } 480 481 //--------------------------------------------------------------------- 482 // Convenience methods for working with formatted Strings 483 //--------------------------------------------------------------------- 484 485 /** 486 * Quote the given {@code String} with single quotes. 487 * @param str the input {@code String} (e.g. "myString") 488 * @return the quoted {@code String} (e.g. "'myString'"), 489 * or {@code null} if the input was {@code null} 490 */ 491 @Nullable 492 public static String quote(@Nullable String str) { 493 return (str != null ? "'" + str + "'" : null); 494 } 495 496 /** 497 * Turn the given Object into a {@code String} with single quotes 498 * if it is a {@code String}; keeping the Object as-is else. 499 * @param obj the input Object (e.g. "myString") 500 * @return the quoted {@code String} (e.g. "'myString'"), 501 * or the input object as-is if not a {@code String} 502 */ 503 @Nullable 504 public static Object quoteIfString(@Nullable Object obj) { 505 return (obj instanceof String ? quote((String) obj) : obj); 506 } 507 508 /** 509 * Unqualify a string qualified by a '.' dot character. For example, 510 * "this.name.is.qualified", returns "qualified". 511 * @param qualifiedName the qualified name 512 */ 513 public static String unqualify(String qualifiedName) { 514 return unqualify(qualifiedName, '.'); 515 } 516 517 /** 518 * Unqualify a string qualified by a separator character. For example, 519 * "this:name:is:qualified" returns "qualified" if using a ':' separator. 520 * @param qualifiedName the qualified name 521 * @param separator the separator 522 */ 523 public static String unqualify(String qualifiedName, char separator) { 524 return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1); 525 } 526 527 /** 528 * Capitalize a {@code String}, changing the first letter to 529 * upper case as per {@link Character#toUpperCase(char)}. 530 * No other letters are changed. 531 * @param str the {@code String} to capitalize 532 * @return the capitalized {@code String} 533 */ 534 public static String capitalize(String str) { 535 return changeFirstCharacterCase(str, true); 536 } 537 538 /** 539 * Uncapitalize a {@code String}, changing the first letter to 540 * lower case as per {@link Character#toLowerCase(char)}. 541 * No other letters are changed. 542 * @param str the {@code String} to uncapitalize 543 * @return the uncapitalized {@code String} 544 */ 545 public static String uncapitalize(String str) { 546 return changeFirstCharacterCase(str, false); 547 } 548 549 private static String changeFirstCharacterCase(String str, boolean capitalize) { 550 if (!hasLength(str)) { 551 return str; 552 } 553 554 char baseChar = str.charAt(0); 555 char updatedChar; 556 if (capitalize) { 557 updatedChar = Character.toUpperCase(baseChar); 558 } 559 else { 560 updatedChar = Character.toLowerCase(baseChar); 561 } 562 if (baseChar == updatedChar) { 563 return str; 564 } 565 566 char[] chars = str.toCharArray(); 567 chars[0] = updatedChar; 568 return new String(chars, 0, chars.length); 569 } 570 571 /** 572 * Extract the filename from the given Java resource path, 573 * e.g. {@code "mypath/myfile.txt" -> "myfile.txt"}. 574 * @param path the file path (may be {@code null}) 575 * @return the extracted filename, or {@code null} if none 576 */ 577 @Nullable 578 public static String getFilename(@Nullable String path) { 579 if (path == null) { 580 return null; 581 } 582 583 int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR); 584 return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path); 585 } 586 587 /** 588 * Extract the filename extension from the given Java resource path, 589 * e.g. "mypath/myfile.txt" -> "txt". 590 * @param path the file path (may be {@code null}) 591 * @return the extracted filename extension, or {@code null} if none 592 */ 593 @Nullable 594 public static String getFilenameExtension(@Nullable String path) { 595 if (path == null) { 596 return null; 597 } 598 599 int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); 600 if (extIndex == -1) { 601 return null; 602 } 603 604 int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR); 605 if (folderIndex > extIndex) { 606 return null; 607 } 608 609 return path.substring(extIndex + 1); 610 } 611 612 /** 613 * Strip the filename extension from the given Java resource path, 614 * e.g. "mypath/myfile.txt" -> "mypath/myfile". 615 * @param path the file path 616 * @return the path with stripped filename extension 617 */ 618 public static String stripFilenameExtension(String path) { 619 int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); 620 if (extIndex == -1) { 621 return path; 622 } 623 624 int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR); 625 if (folderIndex > extIndex) { 626 return path; 627 } 628 629 return path.substring(0, extIndex); 630 } 631 632 /** 633 * Apply the given relative path to the given Java resource path, 634 * assuming standard Java folder separation (i.e. "/" separators). 635 * @param path the path to start from (usually a full file path) 636 * @param relativePath the relative path to apply 637 * (relative to the full file path above) 638 * @return the full file path that results from applying the relative path 639 */ 640 public static String applyRelativePath(String path, String relativePath) { 641 int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR); 642 if (separatorIndex != -1) { 643 String newPath = path.substring(0, separatorIndex); 644 if (!relativePath.startsWith(FOLDER_SEPARATOR)) { 645 newPath += FOLDER_SEPARATOR; 646 } 647 return newPath + relativePath; 648 } 649 else { 650 return relativePath; 651 } 652 } 653 654 /** 655 * Normalize the path by suppressing sequences like "path/.." and 656 * inner simple dots. 657 * <p>The result is convenient for path comparison. For other uses, 658 * notice that Windows separators ("\") are replaced by simple slashes. 659 * <p><strong>NOTE</strong> that {@code cleanPath} should not be depended 660 * upon in a security context. Other mechanisms should be used to prevent 661 * path-traversal issues. 662 * @param path the original path 663 * @return the normalized path 664 */ 665 public static String cleanPath(String path) { 666 if (!hasLength(path)) { 667 return path; 668 } 669 String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); 670 671 // Shortcut if there is no work to do 672 if (pathToUse.indexOf('.') == -1) { 673 return pathToUse; 674 } 675 676 // Strip prefix from path to analyze, to not treat it as part of the 677 // first path element. This is necessary to correctly parse paths like 678 // "file:core/../core/io/Resource.class", where the ".." should just 679 // strip the first "core" directory while keeping the "file:" prefix. 680 int prefixIndex = pathToUse.indexOf(':'); 681 String prefix = ""; 682 if (prefixIndex != -1) { 683 prefix = pathToUse.substring(0, prefixIndex + 1); 684 if (prefix.contains(FOLDER_SEPARATOR)) { 685 prefix = ""; 686 } 687 else { 688 pathToUse = pathToUse.substring(prefixIndex + 1); 689 } 690 } 691 if (pathToUse.startsWith(FOLDER_SEPARATOR)) { 692 prefix = prefix + FOLDER_SEPARATOR; 693 pathToUse = pathToUse.substring(1); 694 } 695 696 String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR); 697 Deque<String> pathElements = new ArrayDeque<>(); 698 int tops = 0; 699 700 for (int i = pathArray.length - 1; i >= 0; i--) { 701 String element = pathArray[i]; 702 if (CURRENT_PATH.equals(element)) { 703 // Points to current directory - drop it. 704 } 705 else if (TOP_PATH.equals(element)) { 706 // Registering top path found. 707 tops++; 708 } 709 else { 710 if (tops > 0) { 711 // Merging path element with element corresponding to top path. 712 tops--; 713 } 714 else { 715 // Normal path element found. 716 pathElements.addFirst(element); 717 } 718 } 719 } 720 721 // All path elements stayed the same - shortcut 722 if (pathArray.length == pathElements.size()) { 723 return prefix + pathToUse; 724 } 725 // Remaining top paths need to be retained. 726 for (int i = 0; i < tops; i++) { 727 pathElements.addFirst(TOP_PATH); 728 } 729 // If nothing else left, at least explicitly point to current path. 730 if (pathElements.size() == 1 && pathElements.getLast().isEmpty() && !prefix.endsWith(FOLDER_SEPARATOR)) { 731 pathElements.addFirst(CURRENT_PATH); 732 } 733 734 return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR); 735 } 736 737 /** 738 * Compare two paths after normalization of them. 739 * @param path1 first path for comparison 740 * @param path2 second path for comparison 741 * @return whether the two paths are equivalent after normalization 742 */ 743 public static boolean pathEquals(String path1, String path2) { 744 return cleanPath(path1).equals(cleanPath(path2)); 745 } 746 747 /** 748 * Decode the given encoded URI component value. Based on the following rules: 749 * <ul> 750 * <li>Alphanumeric characters {@code "a"} through {@code "z"}, {@code "A"} through {@code "Z"}, 751 * and {@code "0"} through {@code "9"} stay the same.</li> 752 * <li>Special characters {@code "-"}, {@code "_"}, {@code "."}, and {@code "*"} stay the same.</li> 753 * <li>A sequence "{@code %<i>xy</i>}" is interpreted as a hexadecimal representation of the character.</li> 754 * </ul> 755 * @param source the encoded String 756 * @param charset the character set 757 * @return the decoded value 758 * @throws IllegalArgumentException when the given source contains invalid encoded sequences 759 * @since 5.0 760 * @see java.net.URLDecoder#decode(String, String) 761 */ 762 public static String uriDecode(String source, Charset charset) { 763 int length = source.length(); 764 if (length == 0) { 765 return source; 766 } 767 Assert.notNull(charset, "Charset must not be null"); 768 769 ByteArrayOutputStream baos = new ByteArrayOutputStream(length); 770 boolean changed = false; 771 for (int i = 0; i < length; i++) { 772 int ch = source.charAt(i); 773 if (ch == '%') { 774 if (i + 2 < length) { 775 char hex1 = source.charAt(i + 1); 776 char hex2 = source.charAt(i + 2); 777 int u = Character.digit(hex1, 16); 778 int l = Character.digit(hex2, 16); 779 if (u == -1 || l == -1) { 780 throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); 781 } 782 baos.write((char) ((u << 4) + l)); 783 i += 2; 784 changed = true; 785 } 786 else { 787 throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\""); 788 } 789 } 790 else { 791 baos.write(ch); 792 } 793 } 794 return (changed ? StreamUtils.copyToString(baos, charset) : source); 795 } 796 797 /** 798 * Parse the given {@code String} value into a {@link Locale}, accepting 799 * the {@link Locale#toString} format as well as BCP 47 language tags. 800 * @param localeValue the locale value: following either {@code Locale's} 801 * {@code toString()} format ("en", "en_UK", etc), also accepting spaces as 802 * separators (as an alternative to underscores), or BCP 47 (e.g. "en-UK") 803 * as specified by {@link Locale#forLanguageTag} on Java 7+ 804 * @return a corresponding {@code Locale} instance, or {@code null} if none 805 * @throws IllegalArgumentException in case of an invalid locale specification 806 * @since 5.0.4 807 * @see #parseLocaleString 808 * @see Locale#forLanguageTag 809 */ 810 @Nullable 811 public static Locale parseLocale(String localeValue) { 812 String[] tokens = tokenizeLocaleSource(localeValue); 813 if (tokens.length == 1) { 814 validateLocalePart(localeValue); 815 Locale resolved = Locale.forLanguageTag(localeValue); 816 if (resolved.getLanguage().length() > 0) { 817 return resolved; 818 } 819 } 820 return parseLocaleTokens(localeValue, tokens); 821 } 822 823 /** 824 * Parse the given {@code String} representation into a {@link Locale}. 825 * <p>For many parsing scenarios, this is an inverse operation of 826 * {@link Locale#toString Locale's toString}, in a lenient sense. 827 * This method does not aim for strict {@code Locale} design compliance; 828 * it is rather specifically tailored for typical Spring parsing needs. 829 * <p><b>Note: This delegate does not accept the BCP 47 language tag format. 830 * Please use {@link #parseLocale} for lenient parsing of both formats.</b> 831 * @param localeString the locale {@code String}: following {@code Locale's} 832 * {@code toString()} format ("en", "en_UK", etc), also accepting spaces as 833 * separators (as an alternative to underscores) 834 * @return a corresponding {@code Locale} instance, or {@code null} if none 835 * @throws IllegalArgumentException in case of an invalid locale specification 836 */ 837 @Nullable 838 public static Locale parseLocaleString(String localeString) { 839 return parseLocaleTokens(localeString, tokenizeLocaleSource(localeString)); 840 } 841 842 private static String[] tokenizeLocaleSource(String localeSource) { 843 return tokenizeToStringArray(localeSource, "_ ", false, false); 844 } 845 846 @Nullable 847 private static Locale parseLocaleTokens(String localeString, String[] tokens) { 848 String language = (tokens.length > 0 ? tokens[0] : ""); 849 String country = (tokens.length > 1 ? tokens[1] : ""); 850 validateLocalePart(language); 851 validateLocalePart(country); 852 853 String variant = ""; 854 if (tokens.length > 2) { 855 // There is definitely a variant, and it is everything after the country 856 // code sans the separator between the country code and the variant. 857 int endIndexOfCountryCode = localeString.indexOf(country, language.length()) + country.length(); 858 // Strip off any leading '_' and whitespace, what's left is the variant. 859 variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode)); 860 if (variant.startsWith("_")) { 861 variant = trimLeadingCharacter(variant, '_'); 862 } 863 } 864 865 if (variant.isEmpty() && country.startsWith("#")) { 866 variant = country; 867 country = ""; 868 } 869 870 return (language.length() > 0 ? new Locale(language, country, variant) : null); 871 } 872 873 private static void validateLocalePart(String localePart) { 874 for (int i = 0; i < localePart.length(); i++) { 875 char ch = localePart.charAt(i); 876 if (ch != ' ' && ch != '_' && ch != '-' && ch != '#' && !Character.isLetterOrDigit(ch)) { 877 throw new IllegalArgumentException( 878 "Locale part \"" + localePart + "\" contains invalid characters"); 879 } 880 } 881 } 882 883 /** 884 * Determine the RFC 3066 compliant language tag, 885 * as used for the HTTP "Accept-Language" header. 886 * @param locale the Locale to transform to a language tag 887 * @return the RFC 3066 compliant language tag as {@code String} 888 * @deprecated as of 5.0.4, in favor of {@link Locale#toLanguageTag()} 889 */ 890 @Deprecated 891 public static String toLanguageTag(Locale locale) { 892 return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : ""); 893 } 894 895 /** 896 * Parse the given {@code timeZoneString} value into a {@link TimeZone}. 897 * @param timeZoneString the time zone {@code String}, following {@link TimeZone#getTimeZone(String)} 898 * but throwing {@link IllegalArgumentException} in case of an invalid time zone specification 899 * @return a corresponding {@link TimeZone} instance 900 * @throws IllegalArgumentException in case of an invalid time zone specification 901 */ 902 public static TimeZone parseTimeZoneString(String timeZoneString) { 903 TimeZone timeZone = TimeZone.getTimeZone(timeZoneString); 904 if ("GMT".equals(timeZone.getID()) && !timeZoneString.startsWith("GMT")) { 905 // We don't want that GMT fallback... 906 throw new IllegalArgumentException("Invalid time zone specification '" + timeZoneString + "'"); 907 } 908 return timeZone; 909 } 910 911 912 //--------------------------------------------------------------------- 913 // Convenience methods for working with String arrays 914 //--------------------------------------------------------------------- 915 916 /** 917 * Copy the given {@link Collection} into a {@code String} array. 918 * <p>The {@code Collection} must contain {@code String} elements only. 919 * @param collection the {@code Collection} to copy 920 * (potentially {@code null} or empty) 921 * @return the resulting {@code String} array 922 */ 923 public static String[] toStringArray(@Nullable Collection<String> collection) { 924 return (!CollectionUtils.isEmpty(collection) ? collection.toArray(EMPTY_STRING_ARRAY) : EMPTY_STRING_ARRAY); 925 } 926 927 /** 928 * Copy the given {@link Enumeration} into a {@code String} array. 929 * <p>The {@code Enumeration} must contain {@code String} elements only. 930 * @param enumeration the {@code Enumeration} to copy 931 * (potentially {@code null} or empty) 932 * @return the resulting {@code String} array 933 */ 934 public static String[] toStringArray(@Nullable Enumeration<String> enumeration) { 935 return (enumeration != null ? toStringArray(Collections.list(enumeration)) : EMPTY_STRING_ARRAY); 936 } 937 938 /** 939 * Append the given {@code String} to the given {@code String} array, 940 * returning a new array consisting of the input array contents plus 941 * the given {@code String}. 942 * @param array the array to append to (can be {@code null}) 943 * @param str the {@code String} to append 944 * @return the new array (never {@code null}) 945 */ 946 public static String[] addStringToArray(@Nullable String[] array, String str) { 947 if (ObjectUtils.isEmpty(array)) { 948 return new String[] {str}; 949 } 950 951 String[] newArr = new String[array.length + 1]; 952 System.arraycopy(array, 0, newArr, 0, array.length); 953 newArr[array.length] = str; 954 return newArr; 955 } 956 957 /** 958 * Concatenate the given {@code String} arrays into one, 959 * with overlapping array elements included twice. 960 * <p>The order of elements in the original arrays is preserved. 961 * @param array1 the first array (can be {@code null}) 962 * @param array2 the second array (can be {@code null}) 963 * @return the new array ({@code null} if both given arrays were {@code null}) 964 */ 965 @Nullable 966 public static String[] concatenateStringArrays(@Nullable String[] array1, @Nullable String[] array2) { 967 if (ObjectUtils.isEmpty(array1)) { 968 return array2; 969 } 970 if (ObjectUtils.isEmpty(array2)) { 971 return array1; 972 } 973 974 String[] newArr = new String[array1.length + array2.length]; 975 System.arraycopy(array1, 0, newArr, 0, array1.length); 976 System.arraycopy(array2, 0, newArr, array1.length, array2.length); 977 return newArr; 978 } 979 980 /** 981 * Merge the given {@code String} arrays into one, with overlapping 982 * array elements only included once. 983 * <p>The order of elements in the original arrays is preserved 984 * (with the exception of overlapping elements, which are only 985 * included on their first occurrence). 986 * @param array1 the first array (can be {@code null}) 987 * @param array2 the second array (can be {@code null}) 988 * @return the new array ({@code null} if both given arrays were {@code null}) 989 * @deprecated as of 4.3.15, in favor of manual merging via {@link LinkedHashSet} 990 * (with every entry included at most once, even entries within the first array) 991 */ 992 @Deprecated 993 @Nullable 994 public static String[] mergeStringArrays(@Nullable String[] array1, @Nullable String[] array2) { 995 if (ObjectUtils.isEmpty(array1)) { 996 return array2; 997 } 998 if (ObjectUtils.isEmpty(array2)) { 999 return array1; 1000 } 1001 1002 List<String> result = new ArrayList<>(Arrays.asList(array1)); 1003 for (String str : array2) { 1004 if (!result.contains(str)) { 1005 result.add(str); 1006 } 1007 } 1008 return toStringArray(result); 1009 } 1010 1011 /** 1012 * Sort the given {@code String} array if necessary. 1013 * @param array the original array (potentially empty) 1014 * @return the array in sorted form (never {@code null}) 1015 */ 1016 public static String[] sortStringArray(String[] array) { 1017 if (ObjectUtils.isEmpty(array)) { 1018 return array; 1019 } 1020 1021 Arrays.sort(array); 1022 return array; 1023 } 1024 1025 /** 1026 * Trim the elements of the given {@code String} array, calling 1027 * {@code String.trim()} on each non-null element. 1028 * @param array the original {@code String} array (potentially empty) 1029 * @return the resulting array (of the same size) with trimmed elements 1030 */ 1031 public static String[] trimArrayElements(String[] array) { 1032 if (ObjectUtils.isEmpty(array)) { 1033 return array; 1034 } 1035 1036 String[] result = new String[array.length]; 1037 for (int i = 0; i < array.length; i++) { 1038 String element = array[i]; 1039 result[i] = (element != null ? element.trim() : null); 1040 } 1041 return result; 1042 } 1043 1044 /** 1045 * Remove duplicate strings from the given array. 1046 * <p>As of 4.2, it preserves the original order, as it uses a {@link LinkedHashSet}. 1047 * @param array the {@code String} array (potentially empty) 1048 * @return an array without duplicates, in natural sort order 1049 */ 1050 public static String[] removeDuplicateStrings(String[] array) { 1051 if (ObjectUtils.isEmpty(array)) { 1052 return array; 1053 } 1054 1055 Set<String> set = new LinkedHashSet<>(Arrays.asList(array)); 1056 return toStringArray(set); 1057 } 1058 1059 /** 1060 * Split a {@code String} at the first occurrence of the delimiter. 1061 * Does not include the delimiter in the result. 1062 * @param toSplit the string to split (potentially {@code null} or empty) 1063 * @param delimiter to split the string up with (potentially {@code null} or empty) 1064 * @return a two element array with index 0 being before the delimiter, and 1065 * index 1 being after the delimiter (neither element includes the delimiter); 1066 * or {@code null} if the delimiter wasn't found in the given input {@code String} 1067 */ 1068 @Nullable 1069 public static String[] split(@Nullable String toSplit, @Nullable String delimiter) { 1070 if (!hasLength(toSplit) || !hasLength(delimiter)) { 1071 return null; 1072 } 1073 int offset = toSplit.indexOf(delimiter); 1074 if (offset < 0) { 1075 return null; 1076 } 1077 1078 String beforeDelimiter = toSplit.substring(0, offset); 1079 String afterDelimiter = toSplit.substring(offset + delimiter.length()); 1080 return new String[] {beforeDelimiter, afterDelimiter}; 1081 } 1082 1083 /** 1084 * Take an array of strings and split each element based on the given delimiter. 1085 * A {@code Properties} instance is then generated, with the left of the delimiter 1086 * providing the key, and the right of the delimiter providing the value. 1087 * <p>Will trim both the key and value before adding them to the {@code Properties}. 1088 * @param array the array to process 1089 * @param delimiter to split each element using (typically the equals symbol) 1090 * @return a {@code Properties} instance representing the array contents, 1091 * or {@code null} if the array to process was {@code null} or empty 1092 */ 1093 @Nullable 1094 public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) { 1095 return splitArrayElementsIntoProperties(array, delimiter, null); 1096 } 1097 1098 /** 1099 * Take an array of strings and split each element based on the given delimiter. 1100 * A {@code Properties} instance is then generated, with the left of the 1101 * delimiter providing the key, and the right of the delimiter providing the value. 1102 * <p>Will trim both the key and value before adding them to the 1103 * {@code Properties} instance. 1104 * @param array the array to process 1105 * @param delimiter to split each element using (typically the equals symbol) 1106 * @param charsToDelete one or more characters to remove from each element 1107 * prior to attempting the split operation (typically the quotation mark 1108 * symbol), or {@code null} if no removal should occur 1109 * @return a {@code Properties} instance representing the array contents, 1110 * or {@code null} if the array to process was {@code null} or empty 1111 */ 1112 @Nullable 1113 public static Properties splitArrayElementsIntoProperties( 1114 String[] array, String delimiter, @Nullable String charsToDelete) { 1115 1116 if (ObjectUtils.isEmpty(array)) { 1117 return null; 1118 } 1119 1120 Properties result = new Properties(); 1121 for (String element : array) { 1122 if (charsToDelete != null) { 1123 element = deleteAny(element, charsToDelete); 1124 } 1125 String[] splittedElement = split(element, delimiter); 1126 if (splittedElement == null) { 1127 continue; 1128 } 1129 result.setProperty(splittedElement[0].trim(), splittedElement[1].trim()); 1130 } 1131 return result; 1132 } 1133 1134 /** 1135 * Tokenize the given {@code String} into a {@code String} array via a 1136 * {@link StringTokenizer}. 1137 * <p>Trims tokens and omits empty tokens. 1138 * <p>The given {@code delimiters} string can consist of any number of 1139 * delimiter characters. Each of those characters can be used to separate 1140 * tokens. A delimiter is always a single character; for multi-character 1141 * delimiters, consider using {@link #delimitedListToStringArray}. 1142 * @param str the {@code String} to tokenize (potentially {@code null} or empty) 1143 * @param delimiters the delimiter characters, assembled as a {@code String} 1144 * (each of the characters is individually considered as a delimiter) 1145 * @return an array of the tokens 1146 * @see java.util.StringTokenizer 1147 * @see String#trim() 1148 * @see #delimitedListToStringArray 1149 */ 1150 public static String[] tokenizeToStringArray(@Nullable String str, String delimiters) { 1151 return tokenizeToStringArray(str, delimiters, true, true); 1152 } 1153 1154 /** 1155 * Tokenize the given {@code String} into a {@code String} array via a 1156 * {@link StringTokenizer}. 1157 * <p>The given {@code delimiters} string can consist of any number of 1158 * delimiter characters. Each of those characters can be used to separate 1159 * tokens. A delimiter is always a single character; for multi-character 1160 * delimiters, consider using {@link #delimitedListToStringArray}. 1161 * @param str the {@code String} to tokenize (potentially {@code null} or empty) 1162 * @param delimiters the delimiter characters, assembled as a {@code String} 1163 * (each of the characters is individually considered as a delimiter) 1164 * @param trimTokens trim the tokens via {@link String#trim()} 1165 * @param ignoreEmptyTokens omit empty tokens from the result array 1166 * (only applies to tokens that are empty after trimming; StringTokenizer 1167 * will not consider subsequent delimiters as token in the first place). 1168 * @return an array of the tokens 1169 * @see java.util.StringTokenizer 1170 * @see String#trim() 1171 * @see #delimitedListToStringArray 1172 */ 1173 public static String[] tokenizeToStringArray( 1174 @Nullable String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { 1175 1176 if (str == null) { 1177 return EMPTY_STRING_ARRAY; 1178 } 1179 1180 StringTokenizer st = new StringTokenizer(str, delimiters); 1181 List<String> tokens = new ArrayList<>(); 1182 while (st.hasMoreTokens()) { 1183 String token = st.nextToken(); 1184 if (trimTokens) { 1185 token = token.trim(); 1186 } 1187 if (!ignoreEmptyTokens || token.length() > 0) { 1188 tokens.add(token); 1189 } 1190 } 1191 return toStringArray(tokens); 1192 } 1193 1194 /** 1195 * Take a {@code String} that is a delimited list and convert it into a 1196 * {@code String} array. 1197 * <p>A single {@code delimiter} may consist of more than one character, 1198 * but it will still be considered as a single delimiter string, rather 1199 * than as bunch of potential delimiter characters, in contrast to 1200 * {@link #tokenizeToStringArray}. 1201 * @param str the input {@code String} (potentially {@code null} or empty) 1202 * @param delimiter the delimiter between elements (this is a single delimiter, 1203 * rather than a bunch individual delimiter characters) 1204 * @return an array of the tokens in the list 1205 * @see #tokenizeToStringArray 1206 */ 1207 public static String[] delimitedListToStringArray(@Nullable String str, @Nullable String delimiter) { 1208 return delimitedListToStringArray(str, delimiter, null); 1209 } 1210 1211 /** 1212 * Take a {@code String} that is a delimited list and convert it into 1213 * a {@code String} array. 1214 * <p>A single {@code delimiter} may consist of more than one character, 1215 * but it will still be considered as a single delimiter string, rather 1216 * than as bunch of potential delimiter characters, in contrast to 1217 * {@link #tokenizeToStringArray}. 1218 * @param str the input {@code String} (potentially {@code null} or empty) 1219 * @param delimiter the delimiter between elements (this is a single delimiter, 1220 * rather than a bunch individual delimiter characters) 1221 * @param charsToDelete a set of characters to delete; useful for deleting unwanted 1222 * line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a {@code String} 1223 * @return an array of the tokens in the list 1224 * @see #tokenizeToStringArray 1225 */ 1226 public static String[] delimitedListToStringArray( 1227 @Nullable String str, @Nullable String delimiter, @Nullable String charsToDelete) { 1228 1229 if (str == null) { 1230 return EMPTY_STRING_ARRAY; 1231 } 1232 if (delimiter == null) { 1233 return new String[] {str}; 1234 } 1235 1236 List<String> result = new ArrayList<>(); 1237 if (delimiter.isEmpty()) { 1238 for (int i = 0; i < str.length(); i++) { 1239 result.add(deleteAny(str.substring(i, i + 1), charsToDelete)); 1240 } 1241 } 1242 else { 1243 int pos = 0; 1244 int delPos; 1245 while ((delPos = str.indexOf(delimiter, pos)) != -1) { 1246 result.add(deleteAny(str.substring(pos, delPos), charsToDelete)); 1247 pos = delPos + delimiter.length(); 1248 } 1249 if (str.length() > 0 && pos <= str.length()) { 1250 // Add rest of String, but not in case of empty input. 1251 result.add(deleteAny(str.substring(pos), charsToDelete)); 1252 } 1253 } 1254 return toStringArray(result); 1255 } 1256 1257 /** 1258 * Convert a comma delimited list (e.g., a row from a CSV file) into an 1259 * array of strings. 1260 * @param str the input {@code String} (potentially {@code null} or empty) 1261 * @return an array of strings, or the empty array in case of empty input 1262 */ 1263 public static String[] commaDelimitedListToStringArray(@Nullable String str) { 1264 return delimitedListToStringArray(str, ","); 1265 } 1266 1267 /** 1268 * Convert a comma delimited list (e.g., a row from a CSV file) into a set. 1269 * <p>Note that this will suppress duplicates, and as of 4.2, the elements in 1270 * the returned set will preserve the original order in a {@link LinkedHashSet}. 1271 * @param str the input {@code String} (potentially {@code null} or empty) 1272 * @return a set of {@code String} entries in the list 1273 * @see #removeDuplicateStrings(String[]) 1274 */ 1275 public static Set<String> commaDelimitedListToSet(@Nullable String str) { 1276 String[] tokens = commaDelimitedListToStringArray(str); 1277 return new LinkedHashSet<>(Arrays.asList(tokens)); 1278 } 1279 1280 /** 1281 * Convert a {@link Collection} to a delimited {@code String} (e.g. CSV). 1282 * <p>Useful for {@code toString()} implementations. 1283 * @param coll the {@code Collection} to convert (potentially {@code null} or empty) 1284 * @param delim the delimiter to use (typically a ",") 1285 * @param prefix the {@code String} to start each element with 1286 * @param suffix the {@code String} to end each element with 1287 * @return the delimited {@code String} 1288 */ 1289 public static String collectionToDelimitedString( 1290 @Nullable Collection<?> coll, String delim, String prefix, String suffix) { 1291 1292 if (CollectionUtils.isEmpty(coll)) { 1293 return ""; 1294 } 1295 1296 StringBuilder sb = new StringBuilder(); 1297 Iterator<?> it = coll.iterator(); 1298 while (it.hasNext()) { 1299 sb.append(prefix).append(it.next()).append(suffix); 1300 if (it.hasNext()) { 1301 sb.append(delim); 1302 } 1303 } 1304 return sb.toString(); 1305 } 1306 1307 /** 1308 * Convert a {@code Collection} into a delimited {@code String} (e.g. CSV). 1309 * <p>Useful for {@code toString()} implementations. 1310 * @param coll the {@code Collection} to convert (potentially {@code null} or empty) 1311 * @param delim the delimiter to use (typically a ",") 1312 * @return the delimited {@code String} 1313 */ 1314 public static String collectionToDelimitedString(@Nullable Collection<?> coll, String delim) { 1315 return collectionToDelimitedString(coll, delim, "", ""); 1316 } 1317 1318 /** 1319 * Convert a {@code Collection} into a delimited {@code String} (e.g., CSV). 1320 * <p>Useful for {@code toString()} implementations. 1321 * @param coll the {@code Collection} to convert (potentially {@code null} or empty) 1322 * @return the delimited {@code String} 1323 */ 1324 public static String collectionToCommaDelimitedString(@Nullable Collection<?> coll) { 1325 return collectionToDelimitedString(coll, ","); 1326 } 1327 1328 /** 1329 * Convert a {@code String} array into a delimited {@code String} (e.g. CSV). 1330 * <p>Useful for {@code toString()} implementations. 1331 * @param arr the array to display (potentially {@code null} or empty) 1332 * @param delim the delimiter to use (typically a ",") 1333 * @return the delimited {@code String} 1334 */ 1335 public static String arrayToDelimitedString(@Nullable Object[] arr, String delim) { 1336 if (ObjectUtils.isEmpty(arr)) { 1337 return ""; 1338 } 1339 if (arr.length == 1) { 1340 return ObjectUtils.nullSafeToString(arr[0]); 1341 } 1342 1343 StringJoiner sj = new StringJoiner(delim); 1344 for (Object o : arr) { 1345 sj.add(String.valueOf(o)); 1346 } 1347 return sj.toString(); 1348 } 1349 1350 /** 1351 * Convert a {@code String} array into a comma delimited {@code String} 1352 * (i.e., CSV). 1353 * <p>Useful for {@code toString()} implementations. 1354 * @param arr the array to display (potentially {@code null} or empty) 1355 * @return the delimited {@code String} 1356 */ 1357 public static String arrayToCommaDelimitedString(@Nullable Object[] arr) { 1358 return arrayToDelimitedString(arr, ","); 1359 } 1360 1361}