cancel
Showing results for 
Search instead for 
Did you mean: 

UDF read file in JAR Packet

Former Member
0 Kudos

hi,all

I want to use imported JAR packet, in UDF I use the code :

InputStream istr = getClass().getClassLoader().getResourceAsStream("property.txt");

for read file "property.txt" what is in JAR Packet,

Is it correct way ?

Best Regards

-


Hengbing

Accepted Solutions (1)

Accepted Solutions (1)

Former Member
0 Kudos

Hi Hengbing,

That should work for you. You might consider creating a simple java class so you donu2019t have to repeatedly load the properties.


package examples;

import java.io.InputStream;
import java.util.Properties;
import com.sap.aii.utilxi.misc.api.BaseRuntimeException;

public class Example {
  
  private static final String FILE_NAME = "folder/file.properties";
  private static Properties props = null;

  public static String getProperty(String propName) {
    if (props == null) {
      initProps();
      return props.getProperty(propName) + " [load]";
    }
    return props.getProperty(propName) + " [from memory]";
  }

  private static synchronized void initProps() {
    if (props != null)  // previous thread already loaded it.
      return;

    InputStream is = null;
    try {
      is = Example.class.getClassLoader().getResourceAsStream(FILE_NAME);
      if (is != null) {
        props = new Properties();
        props.load(is);
      } else {
        throw new BaseRuntimeException("Failed to load properties file " + FILE_NAME + " - Input stream is null.");
      }
    } catch (Exception ex) {
      throw new BaseRuntimeException("Failed to load properties file " + FILE_NAME + " - Exception: " + ex.getMessage(), ex);
    } finally {
      if (is != null) try { is.close(); } catch (Exception e) {}
    }
  }
}

The code in your UDF would look like this:

String prop = examples.Example.getProperty("myPropName");

-Russ

Answers (0)