我是Hadoop HDFS的新手,并且对Java相当不熟悉,我需要一些帮助。我正在尝试从HDFS读取文件并计算该文件的MD5哈希值。常规Hadoop配置如下。
private FSDataInputStream hdfsDIS;
private FileInputStream FinputStream;
private FileSystem hdfs;
private Configuration myConfig;
myConfig.addResource("/HADOOP_HOME/conf/core-site.xml");
myConfig.addResource("/HADOOP_HOME/conf/hdfs-site.xml");
hdfs = FileSystem.get(new URI("hdfs://NodeName:54310"), myConfig);
hdfsDIS = hdfs.open(hdfsFilePath);
函数
hdfs.open(hdfsFilePath)
返回一个FSDataInputStream
问题是我只能从HDFS中获取
FSDataInputStream
,但是我想从中获取FileInputStream
。下面的代码执行哈希处理部分,并改编自我在StackOverflow上某个地方找到的内容(现在似乎找不到指向它的链接)。
FileInputStream FinputStream = hdfsDIS; // <---This is where the problem is
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
FileChannel channel = FinputStream.getChannel();
ByteBuffer buff = ByteBuffer.allocate(2048);
while(channel.read(buff) != -1){
buff.flip();
md.update(buff);
buff.clear();
}
byte[] hashValue = md.digest();
return toHex(hashValue);
}
catch (NoSuchAlgorithmException e){
return null;
}
catch (IOException e){
return null;
}
我之所以需要
FileInputStream
的原因是因为执行哈希处理的代码使用了FileChannel
,据说可以提高从文件中读取数据的效率。有人可以告诉我如何将
FSDataInputStream
转换为FileInputStream
最佳答案
用作InputStream:
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
byte[] buff = new byte[2048];
int count;
while((count = hdfsDIS.read(buff)) != -1){
md.update(buff, 0, count);
}
byte[] hashValue = md.digest();
return toHex(hashValue);
}
catch (NoSuchAlgorithmException e){
return null;
}
catch (IOException e){
return null;
}
在这种情况下不行。仅当您将数据复制到另一个通道时,如果使用
DirectByteBuffer.
,它只会提高效率。如果您正在处理数据(如此处所示),则没有任何区别。读取仍然是读取。