gpt4 book ai didi

java - HDFS 中的随机读/写

转载 作者:行者123 更新时间:2023-12-01 14:03:01 26 4
gpt4 key购买 nike

我读到,Hadoop HDFS 中不存在随机读取和写入。但是,在 DFSOutputStream 中写入的参数是

void write(byte buf[], int off, int len)
void write(int b)

同样,DFSInputStream 中读取的参数为

int read(byte buf[], int off, int len)

int read()

OffSet 参数可以在对 HDFS 的读/写调用中看到。如果 MapReduce 框架仅用于在最后位置添加数据,为什么需要它? HDFS 中如何使用“offset”参数? HDFS 写入是否始终仅追加?

最佳答案

参数int off并不代表输入文件内的随机点。它实际上是字节[]内的偏移量,从数据将被写入字节[]内的位置开始直到len字节数。 例如,假设你已经写了

byte buf[15];
read(buf, 5, 10);

这将从输入文件的开头读取数据,而不是从文件的第 5 个字节读取数据。但数组buf[]将从第5个字节填充到最后一个字节(5+10)

要交叉检查,您可以为参数关闭使用一些不同的值。无论您为off指定什么值,数据都将始终从文件开头读取(如果您没有明确使用seek)

这里需要注意的一点是数组的大小不能小于off+len

运行此示例以获得清晰的理解:

public class ReadHdfsFile {

public static void main(String[] args) throws IOException {

Configuration conf = new Configuration();
conf.addResource(new Path("/Users/miqbal1/hadoop-eco/hadoop-1.1.2/conf/core-site.xml"));
conf.addResource(new Path("/Users/miqbal1/hadoop-eco/hadoop-1.1.2/conf/hdfs-site.xml"));
FileSystem fs = FileSystem.get(conf);
FSDataInputStream in = fs.open(new Path("/demo.txt"));

//Filling the array b1 from the 5th byte
int charPos = 0;
byte[] b1 = new byte[10];
int bytesRead = in.read(b1, 5, 5);
System.out.println("Bytes Read : " + bytesRead);
String s = new String(b1, "UTF-8");
System.out.println("Printing char by char(you'll see first 5 bytes as blank)...");
for(char c : s.toCharArray()){
System.out.println("Character " + ++charPos + " : " + c);

}
System.out.println();
System.out.println("Changing offset value....");

//Filling the array b2 from the 10th byte
in.seek(0);
charPos = 0;
byte[] b2 = new byte[15];
bytesRead = in.read(b2, 10, 5);
System.out.println("Bytes Read : " + bytesRead);
s = new String(b2, "UTF-8");
System.out.println("Printing char by char(you'll see first 10 bytes as blank)...");
for(char c : s.toCharArray()){
System.out.println("Character " + ++charPos + " : " + c);
}

System.out.println("DONE!!!");
in.close();
fs.close();
}
}

HTH

关于java - HDFS 中的随机读/写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19192059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com