[英]Is there a concise way to create an InputSupplier for an InputStream in Google Guava?
[英]Is there any way to get the hashcode of an InputStream using Guava?
有沒有一種方法可以獲取Java中InputStream的HashCode,我正在嘗試使用PrimeFaces中的<p:fileUpload/>
上傳圖片,將其轉換為HashCode並將其與另一張圖片進行比較。
目前,我正在嘗試這樣做:
public void save(FileUploadEvent event) throws IOException {
HashCode hashCode = null;
HashCode hashCodeCompare = null;
hashCode = Files.asByteSource(new File(event.toString())).hash(Hashing.murmur3_128(50));
hashCodeCompare = Files.asByteSource(new File(FilePathOfFileToCompare)).hash(Hashing.murmur3_128(50));
boolean hashTrueFalse;
if(hashCode.equals(hashCodeCompare)) {
System.out.println("true");
} else{
System.out.println("false");
}
try (InputStream input = event.getFile().getInputstream()) {
String imageName = generateFileName() + "." + fileExtensions(event.getFile().getFileName());
String imageLink = PICTURE_DESTINATION + "\\" + imageName;
Picture picture = new Picture();
picture.setPictureUrl(imageLink);
pictureService.createOrUpdate(picture);
personForm.getCurrentPersonDTO().setPictureDTO(pictureMapper.toDTO(picture));
} catch (IOException e) {
e.printStackTrace();
}
}
有什么方法可以將InputStream
轉換為哈希碼嗎?
您想要做的是ByteStreams.copy(input, Funnels.asOutputStream(hasher))
,其中hasher
是從Hashing.sha256().newHasher()
。 然后,調用hasher.hash()
以獲取生成的HashCode
。
如果要計算包含在其上的字節的哈希值,則必須閱讀InputStream。 首先將InputSteam讀取為byte []。
與番石榴一起使用ByteStreams:
InputStream in = ...;
byte[] bytes = ByteStreams.toByteArray(in);
一種流行的替代方法是使用Commons IO :
InputStream in = ...;
byte[] bytes = IOUtils.toByteArray(in);
然后,您可以在字節數組上調用Arrays.hashCode():
int hash = java.util.Arrays.hashCode(bytes);
但是,您可能會考慮使用SHA256作為哈希函數,因為您不太可能發生沖突:
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] sha256Hash = digest.digest(bytes);
如果您不想將整個流讀取到內存中的字節數組,則可以計算哈希值,因為其他人正在讀取InputStream。 例如,您可能想將InputStream流式傳輸到磁盤並傳輸到db中。 Guava提供了一個包裝InputStream的類,該類可以為您完成HashingInputStream :
首先用HashinInputStream包裝您的InputStream
HashingInputStream hin = new HashingInputStream(Hashing.sha256(), in);
然后以您喜歡的任何方式讀取HashingInputStream
while(hin.read() != -1);
然后從HashingInputStream獲取哈希
byte[] sha256Hash = hin.hash().asBytes();
我建議使用Files.asByteSource(fileSource.getFile()).hash(hashFunction).padToLong()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.