繁体   English   中英

无法使用getResourceAsStream加载文件

[英]Cannot Load the file using getResourceAsStream

我正在尝试学习Apache Avro,并且已经从Avro的简单教程开始。 我正在尝试使用JSON模式加载数据。 以下是我的简单示例-

public class AvroExample {

    public static Schema SCHEMA; // writer's schema
    public static Schema SCHEMA2; // reader's schema

    private String name;
    private int age;
    private String[] mails;
    private AvroExample boss;

    static {
        try {

            SCHEMA = Schema.parse(AvroExample.class.getResourceAsStream("Employee.avsc"));
            SCHEMA2 = Schema.parse(AvroExample.class.getResourceAsStream("Employee2.avsc"));
        } catch (Exception e) {
            System.out.println("Couldn't load a schema: " + e.getMessage());
        }
    }

    // some more code

}

但是以某种方式,这条线总是给我例外-

SCHEMA = Schema.parse(AvroExample.class.getResourceAsStream("Employee.avsc"));

as- Couldn't load a schema: java.lang.NullPointerException

我相信以某种方式,它无法正确加载文件,或者我以错误的方式加载了文件。

这是文件内容-

{
  "type": "record", 
  "name": "Employee", 
  "fields": [
      {"name": "name", "type": "string"},
      {"name": "age", "type": "int"},
      {"name": "emails", "type": {"type": "array", "items": "string"}},
      {"name": "boss", "type": ["Employee","null"]}
  ]
}

下面是我的工作区的图片,它显示了我将这两个avsc文件放在何处-

在此处输入图片说明

有人可以帮我吗?

通过您向我们展示的项目设置,您的类路径可能看起来像

/root
    /Employee.avsc
    /Employee2.avsc
    /com
        /rjamal
            /avro
                /test
                    /AvroExperiment
                        /...

换句话说,这两个avsc文件将位于类路径的根目录下。 方法调用

AvroExample.class.getResourceAsStream("Employee.avsc")

AvroExample类所在的包中查找资源。

要使其相对于类路径的根,请在路径前面加上/

AvroExample.class.getResourceAsStream("/Employee.avsc")

检查javadoc

在委派之前,使用以下算法从给定资源名称构造绝对资源名称:

  • 如果名称以'/'('\\ u002f')开头,则资源的绝对名称是名称中'/'之后的部分。
  • 否则,绝对名称的格式如下: modified_pa​​ckage_name / name

    其中Modifyed_pa​​ckage_name是此对象的软件包名称,用“ /”代替“。”。 ( '\\ u002e')。

强调我的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM