我想使用Java从网络上下载并解析Mapbox PBF文件。如果我手动下载文件,则可以解析它而不会出现任何错误。但是,如果我使用Java代码下载文件,然后尝试解析下载的文件,则会收到以下异常:
Exception in thread "main"
com.google.protobuf.InvalidProtocolBufferException$InvalidWireTypeException: Protocol message tag had invalid wire type.
at com.google.protobuf.InvalidProtocolBufferException.invalidWireType(InvalidProtocolBufferException.java:111)
通过谷歌搜索此错误,有人说文件已损坏。
尝试以编程方式将这种二进制数据写入文件时,是否缺少某些内容?
以下代码显示了我尝试下载文件的两种方式:
技术1
fileURL = "https://api.mapbox.com/v4/mapbox.mapbox-traffic-v1/17/36159/54906.vector.pbf?style=mapbox://styles/fnembhard/ck9inh9df002c1jpnccjg20pw@00&access_token=..."
public void saveFile1(String fileURL, String fileName){
try{
URL testURL = new URL(fileURL);
if(testURL.getHost() != null) {
InputStream in = new URL(fileURL).openStream();
Files.copy(in, Paths.get(fileName), StandardCopyOption.REPLACE_EXISTING);
}
}
catch(Exception e){
e.printStackTrace();
}
}
技术2
public void saveFile2(String fileURL, String fileName){
try {
URL testURL = new URL(fileURL);
if (testURL.getHost() != null) {
InputStream in = new URL(fileURL).openStream();
// File f = new URL(fileURL).getFile();
OutputStream outputStream = new FileOutputStream(fileName);
int byteRead;
while ((byteRead = in.read()) != -1) {
outputStream.write(byteRead);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
请提供您解析protobuf文件的方式吗?
要解析protobuf文件,您需要了解其架构:Generic Parsing of PB in java
如果您要提供给FileDescriptorSet.parseFrom
的字节是二进制protobuf内容(编译模式),则它应该起作用。
如果没有,那么可能是这种情况,您需要运行时.pbf解析器。不幸的是,Java Protobuf库无法直接加载.pbf。
您可以通过将FileDescriptorSet
命令行工具与protoc
选项一起使用来获得已编译的架构。
另请参见:--descriptor_set_out