Skip to content
Advertisement

Is it possible to convert the String “1L” to the corresponding Long value?

I am parsing a config file with the following instructions:

public String getProperty(String key) throws IOException {
  Properties prop = new Properties();
  String path = "path/to/file/file.properties";
  InputStream stream = this.class.getResourceAsStream(path);
  prop.load(stream);
  return prop.getProperty(key);

The returned value, that is a String, is later converted into the expected type from the calling method. How can I convert the String 1L into a Long type?
I tried:

Long.valueOf(this.getProperty(key));

but it raises NumberFormatException. Is there a way to do it?

Advertisement

Answer

Neither Long.parseLong nor Long.valueOf can directly parse 1L.

A workaround: You can implement a simple stripTrailingL function to remove the trailing L and then parse it to Long.

String str = "1234L";
Long yourLong = Long.parseLong(stripTrailingL(str));

public String stripTrailingL(String str) {
    return str.endsWith("L") ? str.substring(0, str.length() - 1) : str;
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement