Class GeneralTools
- 
Field SummaryFieldsModifier and TypeFieldDescriptionstatic final StringString to represent um (but with the proper 'mu' symbol)static final charSmall Greek mu (useful for micrometers)static final charSmall Greek sigma (useful for Gaussian filter sizes, standard deviations)
- 
Method SummaryModifier and TypeMethodDescriptionstatic booleanalmostTheSame(double n1, double n2, double tolerance) Test if two doubles are approximately equal, within a specified tolerance.static StringarrayToString(Object[] array, String delimiter) Convert a String array to a single string, with a specified delimiter string.static StringarrayToString(Locale locale, double[] array, int nDecimalPlaces) Convert a double array to a String using a space as a delimiter.static StringarrayToString(Locale locale, double[] array, String delimiter, int nDecimalPlaces) Convert a double array to string, with a specified number of decimal places.static booleanblankString(String s, boolean trim) Check if a string is blank, i.e.static booleancheckExtensions(String path, String... extensions) Check whether a path ends with one of a number of specified extensions (case insensitive).static doubleclipValue(double value, double min, double max) Clip a value to be within a specific range.static intclipValue(int value, int min, int max) Clip a value to be within a specific range.static NumberFormatcreateFormatter(int nDecimalPlaces) Create a new DecimalFormat that may be used to convert a number to have a maximum of nDecimalPlaces (trailing zeros are not shown).static booleandeleteFile(File fileToDelete, boolean preferTrash) Delete a file, optionally requesting that it be moved to the trash rather than permanently deleted.static StringescapeFilePath(String path) Escape backslashes in an absolute file path - useful when scripting.static longEstimate the current available memory in bytes, based upon the JVM max and the memory currently used.static longEstimate the current used memory.static StringformatNumber(double value, int maxDecimalPlaces) Format a value with a maximum number of decimal places, using the default Locale.static StringformatNumber(Locale locale, double value, int maxDecimalPlaces) Format a value with a maximum number of decimal places, using a specified Locale.static StringgenerateDistinctName(String base, Collection<String> existingNames) Generate a name that is distinct from the names in an existing collection, while being based on a provided name.getExtension(File file) Get filename extension.getExtension(String name) Get extension from a filename.static StringgetNameWithoutExtension(File file) Get the file name with extension removed.static StringDeprecated.static StringgetPackageVersion(Class<?> cls) Try to determine the version of a jar containing a specified class.static VersionGet a representation of QuPath's version, parsed according to the rules of semantic versioning if possible.static StringGet a String representation of QuPath's version, if known.static booleanReturn true if running on macOS and Apple Silicon.static booleanisLinux()Return true if running on Linux.static booleanisMac()Return true if running on macOS.static booleanReturns true for file extensions containing multiple parts (or 'dots').static booleanisValidFilename(String name) Returns true if the output ofstripInvalidFilenameChars(String)matches the provided name, and the name is not null or blank.static booleanReturn true if running on Windows.static final StringGet a string to represent um (but with the proper 'mu' symbol)static intnumNaNs(double[] vals) Count the number of NaN values in an array.Parse the contents of a JSON String.static StringreadFileAsString(File file) Read the entire contents of a file into a single String.static StringreadFileAsString(String path) Read the entire contents of a file given by the specified path into a single String.static StringreadInputStreamAsString(InputStream stream) Read the entire contents of an InputStream into a single String.static StringreadURLAsString(URL url, int timeoutMillis) Read URL as String, with specified timeout in milliseconds.static StringreplaceCurlyQuotes(String text) Replace different kinds of 'curly quote' in a String with straight quotes.static StringreplaceGremlins(String text, CharSequence replacement) Replace non-printable characters from a String with a specified replacement (may be null).static Comparator<String> Comparator for smart String sorting.static <T> voidsmartStringSort(Collection<T> collection) Smart-sort a collection using theObject.toString()method applied to each element.static <T> voidsmartStringSort(Collection<T> collection, Function<T, String> extractor) Smart-sort a collection after extracting a String representation of each element.static String[]splitLines(String s) Split new lines (in a cross-platform way...static StringstripExtension(String path) Strip the extension from a file name or path, leaving the rest of the string unchanged.static StringStrip characters that would make a String invalid as a filename.static longsum(long[] values) Compute the sum of elements in a long array (possibly representing a histogram).static URItoEncodedURI(String path) Try to convert a path to an encoded URI.static PathTry to identify a Path from a URI, dropping any query or fragment elements.static URITry to convert a path to a URI.static StringzapGremlins(String text) Remove non-printable characters from a String.
- 
Field Details- 
SYMBOL_MUpublic static final char SYMBOL_MUSmall Greek mu (useful for micrometers)- See Also:
 
- 
SYMBOL_SIGMApublic static final char SYMBOL_SIGMASmall Greek sigma (useful for Gaussian filter sizes, standard deviations)- See Also:
 
- 
SYMBOL_MICROMETERString to represent um (but with the proper 'mu' symbol)- See Also:
 
 
- 
- 
Method Details- 
getVersionGet a String representation of QuPath's version, if known.- Returns:
- a String representation of the version, or null if the version is unknown
- See Also:
- Implementation Note
- this is the version of the core module containing this class.
 
- 
getSemanticVersionGet a representation of QuPath's version, parsed according to the rules of semantic versioning if possible.- Returns:
- the current version, or null if the version is unknown or cannot be parsed from getVersion()
- See Also:
- Implementation Note
- this is the version of the core module containing this class.
 
- 
getPackageVersionTry to determine the version of a jar containing a specified class. This first checks the implementation version in the package, then looks for a VERSION file stored as a resource.- Parameters:
- cls- class used to identify the package
- Returns:
- the version, if available, or null if no version is known.
 
- 
getExtensionGet filename extension. Some implementation notes:- Note that this is generally 'the final dot and beyond', however this method also handles several important special cases: ".ome.tif", ".ome.tiff" and ".tar.gz".
- The dot is included as the first character.
- No check is performed to see if the file is actually a directory, but if a dot is the final character then no extension is returned.
- The extension is returned as-is, without adjusting to be upper or lower case.
 - Parameters:
- file-
- Returns:
- see #getNameWithoutExtension(File)
 
- 
getExtensionGet extension from a filename. Some implementation notes:- Note that this is generally 'the final dot and beyond', however this method also handles several important special cases: ".ome.tif", ".ome.tiff" and ".tar.gz".
- The dot is included as the first character.
- No check is performed to see if the file is actually a directory, but if a dot is the final character then no extension is returned.
- The extension is returned as-is, without adjusting to be upper or lower case.
 - Parameters:
- name-
- Returns:
- See Also:
 
- 
stripInvalidFilenameCharsStrip characters that would make a String invalid as a filename. This test is very simple, and may not catch all problems; the behavior of the method may improve in future versions.Note that the test is not platform-dependent, and may be stricter than absolutely necessary - for example, by removing newline characters. This can result in some filenames that would be valid on the current platform being modified. This can however be necessary to help retain cross-platform portability. - Parameters:
- name-
- Returns:
- the (possibly-shortened) filename without invalid characters
 
- 
isValidFilenameReturns true if the output ofstripInvalidFilenameChars(String)matches the provided name, and the name is not null or blank.- Parameters:
- name-
- Returns:
- true if the name is expected to be valid, false otherwise
- See Also:
 
- 
getNameWithoutExtensionGet the file name with extension removed. Note that this generally means removing the text including and after the final dot, but also handles specific multi-part file extensions as well.- Parameters:
- file-
- Returns:
- See Also:
 
- 
getNameWithoutExtensionDeprecated.v0.5.0 in favor ofstripExtension(String), which does the same thing but has a more descriptive name. See https://github.com/qupath/qupath/pull/1275 for details.Strip the extension from a file name or path, leaving the rest of the string unchanged.- Parameters:
- name-
- Returns:
- getExtension(File)
 
- 
stripExtensionStrip the extension from a file name or path, leaving the rest of the string unchanged. Note that this generally means removing the text including and after the final dot, but also handles specific multi-part file extensions as well.- Parameters:
- path-
- Returns:
- See Also:
 
- 
isMultipartExtensionReturns true for file extensions containing multiple parts (or 'dots'). Examples include ome.tif and tar.gz, which can be problematic with some file choosers.- Parameters:
- ext-
- Returns:
 
- 
blankStringCheck if a string is blank, i.e. it is null or its length is 0.- Parameters:
- s-
- trim- If true, any string will be trimmed before its length checked.
- Returns:
- True if the string is null or empty.
 
- 
escapeFilePathEscape backslashes in an absolute file path - useful when scripting.- Parameters:
- path-
- Returns:
 
- 
clipValuepublic static int clipValue(int value, int min, int max) Clip a value to be within a specific range.- Parameters:
- value-
- min-
- max-
- Returns:
 
- 
clipValuepublic static double clipValue(double value, double min, double max) Clip a value to be within a specific range.- Parameters:
- value-
- min-
- max-
- Returns:
 
- 
almostTheSamepublic static boolean almostTheSame(double n1, double n2, double tolerance) Test if two doubles are approximately equal, within a specified tolerance.Relies on apache.common's method as the history of this method proved this task not as straightforward as initially thought. Note that this calculation changed in v0.2.0-m4 and in v0.3.0. The behavior prior to v0.2.0-m4 divided the absolute difference by the first value only, which is not robust to differences in the input order or if the first value is negative. The behavior before v0.3.0 returned whether the absolute difference divided by the average is less than the specified tolerance. - Parameters:
- n1-
- n2-
- tolerance-
- Returns:
 
- 
toURITry to convert a path to a URI.This currently does a very simple check for a known scheme at the beginning ("http:", "https:" or ""file:") to see if it can construct the URI directly; if not, it assumes the path refers to a local file (as it generally did in QuPath 0.1.2 and earlier). This method does not encode special characters. - Parameters:
- path-
- Returns:
- Throws:
- URISyntaxException
- See Also:
 
- 
toEncodedURIpublic static URI toEncodedURI(String path) throws URISyntaxException, UnsupportedEncodingException, MalformedURLException Try to convert a path to an encoded URI.URIs do not accept some characters (e.g. "|"). This method will perform a simple check for http:andhttps:schemes at the beginning of the URI. It will then modify the Query (@see Query) to a valid form. Finally, a reconstructed valid URI is returned. Note: this method will only encode the Query part of the URI (i.e. Fragments, if present, will be ignored ).E.g. " https://host?query=first|second" will return "https://host?query%3Dfirst%7Csecond".- Parameters:
- path-
- Returns:
- encodedURI
- Throws:
- URISyntaxException
- UnsupportedEncodingException
- MalformedURLException
 
- 
toPathTry to identify a Path from a URI, dropping any query or fragment elements.This returns the Path if successful and null otherwise (e.g. if the URI does not correspond to a file). There is no check whether the Path exists, and support for an authority is platform-dependent. - Parameters:
- uri-
- Returns:
 
- 
arrayToStringpublic static String arrayToString(Locale locale, double[] array, String delimiter, int nDecimalPlaces) Convert a double array to string, with a specified number of decimal places. Trailing zeros are not included.- Parameters:
- locale-
- array-
- delimiter-
- nDecimalPlaces-
- Returns:
 
- 
arrayToStringConvert a double array to a String using a space as a delimiter.- Parameters:
- locale-
- array-
- nDecimalPlaces-
- Returns:
 
- 
arrayToStringConvert a String array to a single string, with a specified delimiter string.- Parameters:
- array-
- delimiter-
- Returns:
 
- 
splitLinesSplit new lines (in a cross-platform way... i.e. not with s.split("\n"), which is asking for trouble).- Parameters:
- s-
- Returns:
 
- 
createFormatterCreate a new DecimalFormat that may be used to convert a number to have a maximum of nDecimalPlaces (trailing zeros are not shown). Important note: this always formats as 1.234 rather than 1,234 - regardless of Locale. Consequently its results are more predictable... but may not be consistent with other number formatting on the specified platform.- Parameters:
- nDecimalPlaces-
- Returns:
 
- 
formatNumberFormat a value with a maximum number of decimal places, using the default Locale.- Parameters:
- value-
- maxDecimalPlaces-
- Returns:
 
- 
formatNumberFormat a value with a maximum number of decimal places, using a specified Locale.- Parameters:
- locale-
- value-
- maxDecimalPlaces-
- Returns:
 
- 
parseArgStringValuesParse the contents of a JSON String.Note that this is pretty unsophisticated... also, no localization is performed (using Java's Locales, for example) - so that decimal values should be provided in the form 1.234 (and not e.g. 1,234). - Parameters:
- s-
- Returns:
 
- 
micrometerSymbolGet a string to represent um (but with the proper 'mu' symbol)- Returns:
 
- 
readFileAsStringRead the entire contents of a file given by the specified path into a single String.Note that from QuPath v0.3 this assumes UTF8 encoding. Previously, platform-specific encoding was assumed. - Parameters:
- path-
- Returns:
- Throws:
- IOException
 
- 
readFileAsStringRead the entire contents of a file into a single String.Note that from QuPath v0.3 this assumes UTF8 encoding. Previously, platform-specific encoding was assumed. - Parameters:
- file-
- Returns:
- Throws:
- IOException
 
- 
readInputStreamAsStringRead the entire contents of an InputStream into a single String.Note that from QuPath v0.3 this assumes UTF8 encoding. Previously, platform-specific encoding was assumed. - Parameters:
- stream-
- Returns:
- Throws:
- IOException
 
- 
checkExtensionsCheck whether a path ends with one of a number of specified extensions (case insensitive).- Parameters:
- path-
- extensions-
- Returns:
 
- 
isMacpublic static boolean isMac()Return true if running on macOS.- Returns:
 
- 
isAppleSiliconpublic static boolean isAppleSilicon()Return true if running on macOS and Apple Silicon.- Returns:
 
- 
isLinuxpublic static boolean isLinux()Return true if running on Linux.- Returns:
 
- 
isWindowspublic static boolean isWindows()Return true if running on Windows.- Returns:
 
- 
deleteFileDelete a file, optionally requesting that it be moved to the trash rather than permanently deleted.Note that the behavior of this method is system-dependent, and there is no guarantee the file will indeed be moved to the trash. - Parameters:
- fileToDelete-
- preferTrash-
- Returns:
- true if the file is successfully deleted, false otherwise
 
- 
readURLAsStringRead URL as String, with specified timeout in milliseconds.The content type is checked, and an IOException is thrown if this doesn't start with text/plain. - Parameters:
- url-
- timeoutMillis-
- Returns:
- Throws:
- IOException
 
- 
numNaNspublic static int numNaNs(double[] vals) Count the number of NaN values in an array.- Parameters:
- vals-
- Returns:
 
- 
sumpublic static long sum(long[] values) Compute the sum of elements in a long array (possibly representing a histogram).- Parameters:
- values-
- Returns:
 
- 
generateDistinctNameGenerate a name that is distinct from the names in an existing collection, while being based on a provided name.This is useful, for example, when duplicating named items and requiring that the duplicates can be distinguished. The precise way in which the name is derived is implementation-dependent, with the only requirement that it be recognizably derived from the base name. Currently, names are generated in the form "base (i)"whereiis an integer.Note that if the base already has the same form, any existing integer will be stripped away; for example providing "name (1)"as the base will yield the output"name (2)", (assuming this name does not already exist), rather than"name (1) (1)".- Parameters:
- base- the (non-empty) base from which the name should be derived
- existingNames- a collection of names that are already in use, and therefore must be avoided
- Returns:
- the distinct name
 
- 
estimateAvailableMemorypublic static long estimateAvailableMemory()Estimate the current available memory in bytes, based upon the JVM max and the memory currently used.This may be used to help determine whether a memory-hungry operation should be attempted. - Returns:
- the estimated unused memory in bytes
 
- 
estimateUsedMemorypublic static long estimateUsedMemory()Estimate the current used memory.- Returns:
- the estimated allocated memory in bytes
 
- 
smartStringSortSmart-sort a collection using theObject.toString()method applied to each element. SeesmartStringSort(Collection, Function)for more details.- Type Parameters:
- T-
- Parameters:
- collection- collection to be sorted (results are retained in-place)
- See Also:
 
- 
smartStringSortSmart-sort a collection after extracting a String representation of each element. This differs from a 'normal' sort by splitting the String into lists of numeric and non-numeric parts, and comparing corresponding elements separately. This can sometimes give more intuitive results than a simple String sort, which would treat "10" as 'less than' "2".For example, applying a simple sort to the list ["a1", "a2", "a10"]will result in["a1", "a10", "a2]. Smart-sorting would leave the list unchanged.Note: Currently this method considers only positive integer values, treating characters such as '+', '-', ',', '.' and 'e' as distinct elements of text. - Type Parameters:
- T-
- Parameters:
- collection- collection to be sorted (results are retained in-place)
- extractor- function used to convert each element of the collection to a String representation
 
- 
smartStringComparatorComparator for smart String sorting. Note: This comparator is very inefficient. Where possiblesmartStringSort(Collection, Function)should be used instead.- Returns:
- a String comparator that parses integers from within the String so they may be compared by value
 
- 
zapGremlinsRemove non-printable characters from a String.- Parameters:
- text-
- Returns:
- the modified String, or the original if no changes were made
 
- 
replaceGremlinsReplace non-printable characters from a String with a specified replacement (may be null).- Parameters:
- text- the input text
- replacement- the replacement text (often an empty string or null)
- Returns:
- the modified String, or the original if no changes were made
 
- 
replaceCurlyQuotesReplace different kinds of 'curly quote' in a String with straight quotes. This is particularly useful when working with a script editor.- Parameters:
- text-
- Returns:
- the modified String, or the original if no changes were made
 
 
- 
stripExtension(String), which does the same thing but has a more descriptive name.