【发布时间】:2013-09-30 16:50:51
【问题描述】:
我是 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
【问题讨论】:
-
您是否至少尝试过只是使用现有流进行散列?您说使用
FileChannel“据说”会提高效率——您是否对此进行了测试并发现您实际上需要任何可能获得的性能改进? -
实际上,我没有尝试使用“现有流”,但我想我不妨试试看它是否有效。顺便说一句,我找到了我从 (stackoverflow.com/a/9322214/2105711) 获取代码的链接
-
好的,所以我已经使用了现有的流,从中读取,计算了哈希并且它可以工作。也许我现在可以忘记所谓的“性能改进”。虽然希望有一天有人会想出我正在寻找的使用 NIO FileChannels 的解决方案。 (如果它被认为对大文件有用,那就是)