有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

ApacheSpark如何使用Java读取Hadoop序列文件

我有一个由Spark使用saveAsObjectFile函数生成的序列文件。文件内容只是一些整数。我想用Java在本地阅读。这是我的代码:

    FileSystem fileSystem = null;
    SequenceFile.Reader in = null;
    try {
        fileSystem = FileSystem.get(conf);
        Path path = new Path("D:\\spark_sequence_file");
        in = new SequenceFile.Reader(conf, SequenceFile.Reader.file(path));
        Writable key = (Writable)
                ReflectionUtils.newInstance(in.getKeyClass(), conf);
        BytesWritable value = new BytesWritable();
        while (in.next(key, value)) {
            byte[] val_byte = value.getBytes();
            int val = ByteBuffer.wrap(val_byte, 0, 4).getInt();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

但我不能正确地阅读它;我只是得到了所有相同的值,显然它们是错的。这是我的答案

enter image description here

文件头是这样的: enter image description here

有人能帮我吗


共 (1) 个答案

  1. # 1 楼答案

    在Hadoop中,键的类型通常为WritableComparable,值的类型通常为Writable。记住这个基本概念,我用下面的方式阅读序列文件

    Configuration config = new Configuration();
    Path path = new Path(PATH_TO_YOUR_FILE);
    SequenceFile.Reader reader = new SequenceFile.Reader(FileSystem.get(config), path, config);
    WritableComparable key = (WritableComparable) reader.getKeyClass().newInstance();
    Writable value = (Writable) reader.getValueClass().newInstance();
    while (reader.next(key, value))
      // do some thing
    reader.close();
    

    您案例中的数据问题可能是因为您使用saveAsObjectFile()而不是saveAsSequenceFile(String path,scala.Option<Class<? extends org.apache.hadoop.io.compress.CompressionCodec>> codec)的原因

    请尝试使用上述方法,看看问题是否仍然存在