StringUtil not closing Formatter

Motivation:
The StringUtil class creates a Formatter object, but does not close it. There are also a 2 utility methods which would be generally useful.

Modifications:
- Close the Formatter
- Add length and isNullOrEmpty

Result:
No more resource leaks. Additional utility methods.
This commit is contained in:
Scott Mitchell 2015-08-19 13:52:08 -07:00
parent 34dfa7a2d8
commit 9bc322a6a8

View File

@ -51,11 +51,14 @@ public final class StringUtil {
// Determine the newline character of the current platform. // Determine the newline character of the current platform.
String newLine; String newLine;
Formatter formatter = new Formatter();
try { try {
newLine = new Formatter().format("%n").toString(); newLine = formatter.format("%n").toString();
} catch (Exception e) { } catch (Exception e) {
// Should not reach here, but just in case. // Should not reach here, but just in case.
newLine = "\n"; newLine = "\n";
} finally {
formatter.close();
} }
NEWLINE = newLine; NEWLINE = newLine;
@ -374,6 +377,20 @@ public final class StringUtil {
escaped.append(DOUBLE_QUOTE) : value; escaped.append(DOUBLE_QUOTE) : value;
} }
/**
* Get the length of a string, {@code null} input is considered {@code 0} length.
*/
public static int length(String s) {
return s == null ? 0 : s.length();
}
/**
* Determine if a string is {@code null} or {@link String#isEmpty()} returns {@code true}.
*/
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
private static boolean isDoubleQuote(char c) { private static boolean isDoubleQuote(char c) {
return c == DOUBLE_QUOTE; return c == DOUBLE_QUOTE;
} }