0

I am trying to learn Apache Avro and I have started with simple tutorial for Avro. I am trying to use a JSON Schema to load the data. Below is my Simple example-

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

}

But somehow this line, always give me exception-

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

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

I believe somehow, it is not able to load the file properly or I am loading the file in a wrong way.

This is the file content-

{
  "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"]}
  ]
}

Below is the picture of my workspace which shows where I have put those two avsc files-

enter image description here

Can anybody help me with this?

4

1 回答 1

1

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

/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

    其中 modified_pa​​ckage_name 是此对象的包名称,其中 '/' 替换为 '.' ('\u002e')。

强调我的。

于 2013-09-10T21:01:09.530 回答