如何将Java /资源文件获取到InputStream?

时间:2019-07-05 11:20:27

标签: java spring spring-boot

我在src / main / resources(/ resources / files / templates)中有一个Excel文件。我想将其读取到InputStream。我没有为此找到合适的语法。

componentDidMount(){
    if(Platform.OS === 'ios'){
 navigator.geolocation.requestAuthorization()
    }
    //state for opened toggle and combine with android platform
    else if (Platform.OS === 'android') {

      async function requestlocationPermission() {
        try {
          const granted = await PermissionsAndroid.request(
            PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
            {
              title: 'Location permission',
              message:
                'Just for location ',
              buttonNegative: 'Cancel',
              buttonPositive: 'OK',
            },
          );
          if (granted === PermissionsAndroid.RESULTS.GRANTED) {
            console.log('location enabled');
          } else {
            console.log('location denied');
          }
        } catch {
          console.warn(err)
        }
      }
      setInterval(requestlocationPermission(), 2500)

    }
  }

以上操作无效。我认为路径是错误的。如何为存储在资源中的文件提供正确的路径?

2 个答案:

答案 0 :(得分:0)

这个对我有用。

InputStream is = YourClass.class.getClassLoader().getResourceAsStream("relative path to your file starting from resources folder");

答案 1 :(得分:0)

如果您使用任何方法(静态或非静态):

String fn = "/resources/files/censusTemplates/SimpleStandardTemplate.xlsm";
InputStream in = Clazz.class.getResourceAsStream(fn);

Clazz是您所在的班级的名称。


如果您使用的是非静态方法:

String fn = "/resources/files/censusTemplates/SimpleStandardTemplate.xlsm";
InputStream in = getClass().getResourceAsStream(fn);