在Java中是否有任何方法可以生成一个字符串的MD5哈希?
你需要java.security. messagdigest。
调用MessageDigest. getinstance ("MD5")来获取您可以使用的MessageDigest的MD5实例。
计算哈希的方法是:
以字节[]的形式提供整个输入,并使用md.digest(字节)在一次操作中计算哈希。 通过调用md.update(bytes)每次向MessageDigest提供一个字节[]块。当您完成添加输入字节时,计算与的散列 md.digest()。
md.digest()返回的字节[]是MD5散列。
MessageDigest类可以为您提供MD5摘要的实例。
当使用字符串和加密类时,请确保始终指定您希望字节表示的编码。如果只使用string.getBytes(),它将使用平台默认值。(并非所有平台都使用相同的默认值)
import java.security.*;
..
byte[] bytesOfMessage = yourString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] theMD5digest = md.digest(bytesOfMessage);
如果你有很多数据,看看.update(xxx)方法,它可以被重复调用。然后调用.digest()来获得结果散列。
Bombe的答案是正确的,但请注意,除非你绝对必须使用MD5(例如,为了互操作性而被迫使用),否则更好的选择是SHA1,因为MD5长期使用有缺点。
我应该补充一点,SHA1也有理论上的漏洞,但没有那么严重。目前的哈希技术水平是,有许多候选替换哈希函数,但还没有一个成为取代SHA1的标准最佳实践。因此,根据您的需要,建议您使您的哈希算法可配置,以便将来可以替换它。
如果你真的想要返回一个字符串,而不是字节数组,你总是可以这样做:
String plaintext = "your text here";
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
hashtext = "0"+hashtext;
}
如果你不需要最好的安全性,MD5是完全可以的,如果你正在做一些像检查文件完整性这样的事情,那么安全性就不是一个考虑因素。在这种情况下,您可能希望考虑一些更简单和更快的方法,例如Adler32, Java库也支持它。
下面是我如何使用它:
final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(string.getBytes(Charset.forName("UTF8")));
final byte[] resultByte = messageDigest.digest();
final String result = new String(Hex.encodeHex(resultByte));
来自Apache Commons项目的Hex。
发现了这个:
public String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
}
return null;
}
在下面的网站上,我没有功劳,但这是一个有效的解决方案! 对我来说,很多其他的代码都没有正常工作,我最终在哈希中丢失了0。 这一点似乎与PHP相同。 资料来源:http://m2tec.be/blog/2010/02/03/java - md5 -十六进制- 0093年
我只是下载了common -codec.jar,得到了完美的php,比如md5。这是手册。
只需将其导入到您的项目并使用即可
String Url = "your_url";
System.out.println( DigestUtils.md5Hex( Url ) );
结果出来了。
我的回答不是很直白:
private String md5(String s) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(s.getBytes(), 0, s.length());
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032x", i);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
找到了这个解决方案,在从MD5哈希中获得String表示形式方面要干净得多。
import java.security.*;
import java.math.*;
public class MD5 {
public static void main(String args[]) throws Exception{
String s="This is a test";
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(s.getBytes(),0,s.length());
System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16));
}
}
代码是从这里提取出来的。
是我做的…似乎还行-我相信有人会指出错误…
public final class MD5 {
public enum SaltOption {
BEFORE, AFTER, BOTH, NONE;
}
private static final String ALG = "MD5";
//For conversion to 2-char hex
private static final char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
private SaltOption opt;
/**
* Added the SaltOption constructor since everybody
* has their own standards when it comes to salting
* hashes.
*
* This gives the developer the option...
*
* @param option The salt option to use, BEFORE, AFTER, BOTH or NONE.
*/
public MD5(final SaltOption option) {
//TODO: Add Char Encoding options too... I was too lazy!
this.opt = option;
}
/**
*
* Returns the salted MD5 checksum of the text passed in as an argument.
*
* If the salt is an empty byte array - no salt is applied.
*
* @param txt The text to run through the MD5 algorithm.
* @param salt The salt value in bytes.
* @return The salted MD5 checksum as a <code>byte[]</code>
* @throws NoSuchAlgorithmException
*/
private byte[] createChecksum(final String txt, final byte[] salt) throws NoSuchAlgorithmException {
final MessageDigest complete = MessageDigest.getInstance(ALG);
if(opt.equals(SaltOption.BEFORE) || opt.equals(SaltOption.BOTH)) {
complete.update(salt);
}
complete.update(txt.getBytes());
if(opt.equals(SaltOption.AFTER) || opt.equals(SaltOption.BOTH)) {
complete.update(salt);
}
return complete.digest();
}
/**
*
* Returns the salted MD5 checksum of the file passed in as an argument.
*
* If the salt is an empty byte array - no salt is applied.
*
* @param fle The file to run through the MD5 algorithm.
* @param salt The salt value in bytes.
* @return The salted MD5 checksum as a <code>byte[]</code>
* @throws IOException
* @throws NoSuchAlgorithmException
*/
private byte[] createChecksum(final File fle, final byte[] salt)
throws IOException, NoSuchAlgorithmException {
final byte[] buffer = new byte[1024];
final MessageDigest complete = MessageDigest.getInstance(ALG);
if(opt.equals(SaltOption.BEFORE) || opt.equals(SaltOption.BOTH)) {
complete.update(salt);
}
int numRead;
InputStream fis = null;
try {
fis = new FileInputStream(fle);
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
} finally {
if (fis != null) {
fis.close();
}
}
if(opt.equals(SaltOption.AFTER) || opt.equals(SaltOption.BOTH)) {
complete.update(salt);
}
return complete.digest();
}
/**
*
* Efficiently converts a byte array to its 2 char per byte hex equivalent.
*
* This was adapted from JDK code in the Integer class, I just didn't like
* having to use substrings once I got the result...
*
* @param b The byte array to convert
* @return The converted String, 2 chars per byte...
*/
private String convertToHex(final byte[] b) {
int x;
int charPos;
int radix;
int mask;
final char[] buf = new char[32];
final char[] tmp = new char[3];
final StringBuilder md5 = new StringBuilder();
for (int i = 0; i < b.length; i++) {
x = (b[i] & 0xFF) | 0x100;
charPos = 32;
radix = 1 << 4;
mask = radix - 1;
do {
buf[--charPos] = digits[x & mask];
x >>>= 4;
} while (x != 0);
System.arraycopy(buf, charPos, tmp, 0, (32 - charPos));
md5.append(Arrays.copyOfRange(tmp, 1, 3));
}
return md5.toString();
}
/**
*
* Returns the salted MD5 checksum of the file passed in as an argument.
*
* @param fle The file you want want to run through the MD5 algorithm.
* @param salt The salt value in bytes
* @return The salted MD5 checksum as a 2 char per byte HEX <code>String</code>
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public String getMD5Checksum(final File fle, final byte[] salt)
throws NoSuchAlgorithmException, IOException {
return convertToHex(createChecksum(fle, salt));
}
/**
*
* Returns the MD5 checksum of the file passed in as an argument.
*
* @param fle The file you want want to run through the MD5 algorithm.
* @return The MD5 checksum as a 2 char per byte HEX <code>String</code>
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public String getMD5Checksum(final File fle)
throws NoSuchAlgorithmException, IOException {
return convertToHex(createChecksum(fle, new byte[0]));
}
/**
*
* Returns the salted MD5 checksum of the text passed in as an argument.
*
* @param txt The text you want want to run through the MD5 algorithm.
* @param salt The salt value in bytes.
* @return The salted MD5 checksum as a 2 char per byte HEX <code>String</code>
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public String getMD5Checksum(final String txt, final byte[] salt)
throws NoSuchAlgorithmException {
return convertToHex(createChecksum(txt, salt));
}
/**
*
* Returns the MD5 checksum of the text passed in as an argument.
*
* @param txt The text you want want to run through the MD5 algorithm.
* @return The MD5 checksum as a 2 char per byte HEX <code>String</code>
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public String getMD5Checksum(final String txt)
throws NoSuchAlgorithmException {
return convertToHex(createChecksum(txt, new byte[0]));
}
}
我不知道这与阅读这篇文章的人是否相关,但我只是遇到了我想要解决的问题
从给定的URL下载文件和 将其MD5值与已知值进行比较。
我希望只使用JRE类(没有Apache Commons或类似的类)。我在网上快速搜索了一下,并没有看到同时执行这两项任务的示例代码片段,只是分别执行了每项任务。因为这需要读取相同的文件两次,所以我认为有必要编写一些代码来统一这两个任务,在下载文件时实时计算校验和。这是我的结果(如果它不是完美的Java,很抱歉,但我猜你已经明白了):
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.security.DigestOutputStream; // new
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
void downloadFile(String fromURL, String toFile, BigInteger md5)
throws IOException, NoSuchAlgorithmException
{
ReadableByteChannel in = Channels.newChannel(new URL(fromURL).openStream());
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
WritableByteChannel out = Channels.newChannel(
//new FileOutputStream(toFile)); // old
new DigestOutputStream(new FileOutputStream(toFile), md5Digest)); // new
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); // 1 MB
while (in.read(buffer) != -1) {
buffer.flip();
//md5Digest.update(buffer.asReadOnlyBuffer()); // old
out.write(buffer);
buffer.clear();
}
BigInteger md5Actual = new BigInteger(1, md5Digest.digest());
if (! md5Actual.equals(md5))
throw new RuntimeException(
"MD5 mismatch for file " + toFile +
": expected " + md5.toString(16) +
", got " + md5Actual.toString(16)
);
}
Spring中也有一个DigestUtils类:
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/util/DigestUtils.html
这个类包含md5DigestAsHex()方法来完成这项工作。
无论如何,我无意中发现了这一点,因为我想从一个将安装COM组件的程序的自然键合成guid;我希望进行综合,以免管理GUID生命周期。我将使用MD5,然后使用UUID类从中获取一个字符串。(http://stackoverflow.com/questions/2190890/how-can-i-generate-guid-for-a-string-values/12867439提出了这个问题)。
在任何情况下,java.util.UUID都可以从MD5字节中获得一个漂亮的String。
return UUID.nameUUIDFromBytes(md5Bytes).toString();
没必要把事情搞得太复杂。 DigestUtils工作得很好,使您在使用md5散列时感到舒适。
DigestUtils.md5Hex(_hash);
or
DigestUtils.md5(_hash);
您可以使用任何其他加密方法,如sha或md。
另一个选择是使用Guava哈希方法:
Hasher hasher = Hashing.md5().newHasher();
hasher.putString("my string");
byte[] md5 = hasher.hash().asBytes();
如果你已经在用番石榴,这很方便(如果你没有,你可能应该用)。
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5 encryption
*
* @author Hongten
*
*/
public class MD5 {
public static void main(String[] args) {
System.out.println(MD5.getMD5("123456"));
}
/**
* Use md5 encoded code value
*
* @param sInput
* clearly
* @ return md5 encrypted password
*/
public static String getMD5(String sInput) {
String algorithm = "";
if (sInput == null) {
return "null";
}
try {
algorithm = System.getProperty("MD5.algorithm", "MD5");
} catch (SecurityException se) {
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte buffer[] = sInput.getBytes();
for (int count = 0; count < sInput.length(); count++) {
md.update(buffer, 0, count);
}
byte bDigest[] = md.digest();
BigInteger bi = new BigInteger(bDigest);
return (bi.toString(16));
}
}
Codingkit上有一篇关于这个的文章。查看:http://codingkit.com/a/JAVA/2013/1020/2216.html
你可以试着跟着走。查看详细信息和下载代码:http://jkssweetlife.com/java-hashgenerator-md5-sha-1/
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static void main(String[] args) throws Exception {
final String inputString = "Hello MD5";
System.out.println("MD5 hex for '" + inputString + "' :");
System.out.println(getMD5Hex(inputString));
}
public static String getMD5Hex(final String inputString) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(inputString.getBytes());
byte[] digest = md.digest();
return convertByteToHex(digest);
}
private static String convertByteToHex(byte[] byteData) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
另一个实现:
import javax.xml.bind.DatatypeConverter;
String hash = DatatypeConverter.printHexBinary(
MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
我有一个类(哈希)在哈希格式转换纯文本:md5或sha1,类似于php函数(md5, sha1):
public class Hash {
/**
*
* @param txt, text in plain format
* @param hashType MD5 OR SHA1
* @return hash in hashType
*/
public static String getHash(String txt, String hashType) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance(hashType);
byte[] array = md.digest(txt.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
//error action
}
return null;
}
public static String md5(String txt) {
return Hash.getHash(txt, "MD5");
}
public static String sha1(String txt) {
return Hash.getHash(txt, "SHA1");
}
}
使用JUnit和PHP进行测试
PHP脚本:
<?php
echo 'MD5 :' . md5('Hello World') . "\n";
echo 'SHA1:' . sha1('Hello World') . "\n";
输出PHP脚本:
MD5 :b10a8db164e0754105b7a99be72e3fe5
SHA1:0a4d55a8d778e5022fab701977c5d840bbc486d0
使用JUnit进行示例和测试:
public class HashTest {
@Test
public void test() {
String txt = "Hello World";
assertEquals("b10a8db164e0754105b7a99be72e3fe5", Hash.md5(txt));
assertEquals("0a4d55a8d778e5022fab701977c5d840bbc486d0", Hash.sha1(txt));
}
}
GitHub中的代码
https://github.com/fitorec/java-hashes
试试这个:
public static String getHashMD5(String string) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
BigInteger bi = new BigInteger(1, md.digest(string.getBytes()));
return bi.toString(16);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(MD5Utils.class
.getName()).log(Level.SEVERE, null, ex);
return "";
}
}
我发现这是最清晰和简洁的方法:
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(StandardCharsets.UTF_8.encode(string));
return String.format("%032x", new BigInteger(1, md5.digest()));
这就是我来这里的目的-一个方便的scala函数,返回MD5哈希字符串:
def md5(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}
不像PHP,你可以通过调用MD5函数ie MD5 ($text)来对文本进行MD5哈希,在Java中它有点复杂。我通常通过调用一个返回md5哈希文本的函数来实现它。 首先在你的主类中创建一个名为md5hashing的函数,如下所示。
public static String md5hashing(String text)
{ String hashtext = null;
try
{
String plaintext = text;
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
hashtext = "0"+hashtext;
}
} catch (Exception e1)
{
// TODO: handle exception
JOptionPane.showMessageDialog(null,e1.getClass().getName() + ": " + e1.getMessage());
}
return hashtext;
}
现在,在需要时调用该函数,如下所示。
String text = textFieldName.getText();
String pass = md5hashing(text);
在这里,您可以看到hashtext被附加了一个0,以使其与PHP中的md5散列匹配。
private String hashuj(String dane) throws ServletException{
try {
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] bufor = dane.getBytes();
m.update(bufor,0,bufor.length);
BigInteger hash = new BigInteger(1,m.dige`enter code here`st());
return String.format("%1$032X", hash);
} catch (NoSuchAlgorithmException nsae) {
throw new ServletException("Algorytm szyfrowania nie jest obsługiwany!");
}
}
这个函数给出了与你从mysql的md5函数或php的md5函数等中得到的相同的md5。这是我用的(你可以根据你的需要来改变)
public static String md5( String input ) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(input.getBytes( "UTF-8" ));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
sb.append( String.format( "%02x", array[i]));
}
return sb.toString();
} catch ( NoSuchAlgorithmException | UnsupportedEncodingException e) {
return null;
}
}
import java.security.MessageDigest
val digest = MessageDigest.getInstance("MD5")
//Quick MD5 of text
val text = "MD5 this text!"
val md5hash1 = digest.digest(text.getBytes).map("%02x".format(_)).mkString
//MD5 of text with updates
digest.update("MD5 ".getBytes())
digest.update("this ".getBytes())
digest.update("text!".getBytes())
val md5hash2 = digest.digest().map(0xFF & _).map("%02x".format(_)).mkString
//Output
println(md5hash1 + " should be the same as " + md5hash2)
import java.security.*;
import javax.xml.bind.*;
byte[] bytesOfMessage = yourString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytesOfDigest = md.digest(bytesOfMessage);
String digest = DatatypeConverter.printHexBinary(bytesOfDigest).toLowerCase();
通过使用java中的MessageDigest类中的方法,可以为给定的文本生成MD5散列。安全包。下面是完整的代码片段,
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class MD5HashGenerator
{
public static void main(String args[]) throws NoSuchAlgorithmException
{
String stringToHash = "MyJavaCode";
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(stringToHash.getBytes());
byte[] digiest = messageDigest.digest();
String hashedOutput = DatatypeConverter.printHexBinary(digiest);
System.out.println(hashedOutput);
}
}
MD5函数的输出是由32个十六进制数表示的128位哈希。
如果你使用的是像MySQL这样的数据库,你也可以用一种更简单的方式来做到这一点。查询Select MD5(" text here ")将返回括号中文本的MD5哈希值。
我已经使用php,如下所示
<?php
$goodtext = "Not found";
// If there is no parameter, this code is all skipped
if ( isset($_GET['md5']) ) {
$time_pre = microtime(true);
$md5 = $_GET['md5'];
// This is our alphabet
$txt = "0123456789";
$show = 15;
// Outer loop go go through the alphabet for the
// first position in our "possible" pre-hash
// text
for($i=0; $i<strlen($txt); $i++ ) {
$ch1 = $txt[$i]; // The first of two characters
// Our inner loop Note the use of new variables
// $j and $ch2
for($j=0; $j<strlen($txt); $j++ ) {
$ch2 = $txt[$j]; // Our second character
for($k=0; $k<strlen($txt); $k++ ) {
$ch3 = $txt[$k];
for($l=0; $l<strlen($txt); $l++){
$ch4 = $txt[$l];
// Concatenate the two characters together to
// form the "possible" pre-hash text
$try = $ch1.$ch2.$ch3.$ch4;
// Run the hash and then check to see if we match
$check = hash('md5', $try);
if ( $check == $md5 ) {
$goodtext = $try;
break; // Exit the inner loop
}
// Debug output until $show hits 0
if ( $show > 0 ) {
print "$check $try\n";
$show = $show - 1;
}
if($goodtext == $try){
break;
}
}
if($goodtext == $try){
break;
}
}
if($goodtext == $try) {
break;
}
}
if($goodtext == $try){
break;
}
}
// Compute ellapsed time
$time_post = microtime(true);
print "Ellapsed time: ";
print $time_post-$time_pre;
print "\n";
}
?>
你可以参考这个资料来源
你可以试试凯撒。
第一选择:
byte[] hash =
new Hash(
new ImmutableMessageDigest(
MessageDigest.getInstance("MD5")
),
new PlainText("String to hash...")
).asArray();
第二选择:
byte[] hash =
new ImmutableMessageDigest(
MessageDigest.getInstance("MD5")
).update(
new PlainText("String to hash...")
).digest();
使用java.security.MessageDigest库的简单函数
public String stringMD5Hash(String text) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] bytes = messageDigest.digest(text.getBytes());
StringJoiner stringJoiner = new StringJoiner("");
for (byte b : bytes) {
stringJoiner.add(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
}
return stringJoiner.toString();
}
对于文件使用这个函数
public static String FileMD5Hash(File file) throws NoSuchAlgorithmException, IOException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] bytes = messageDigest.digest(getFileBytes(file));
StringJoiner stringJoiner = new StringJoiner("");
for (byte b : bytes) {
stringJoiner.add(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
}
return stringJoiner.toString();
}
public static byte[] getFileBytes(File file) throws IOException{
InputStream inputStream = new FileInputStream(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, bytesRead);
}
return byteArrayOutputStream.toByteArray();
}
推荐文章
- 到底是什么导致了堆栈溢出错误?
- 为什么Android工作室说“等待调试器”如果我不调试?
- Java:路径vs文件
- ExecutorService,如何等待所有任务完成
- Maven依赖Servlet 3.0 API?
- 如何在IntelliJ IDEA中添加目录到应用程序运行概要文件中的类路径?
- getter和setter是糟糕的设计吗?相互矛盾的建议
- Android room persistent: AppDatabase_Impl不存在
- Java的String[]在Kotlin中等价于什么?
- Intellij IDEA上的System.out.println()快捷方式
- 使用Spring RestTemplate获取JSON对象列表
- Spring JPA选择特定的列
- URLEncoder不能翻译空格字符
- Java中的super()
- 如何转换JSON字符串映射<字符串,字符串>与杰克逊JSON