Java reading a file into memory and how not to explode memory

I am a little new to Java and I am trying to do the MAC calculation in a file. Now, since the file size is unknown at runtime, I cannot just load the entire file into memory. So I wrote code to read in bits (in this case 4k). The problem I am facing is trying to load the entire file into memory to check if both methods give the same hash. However, they seem to produce different hashes

Here is the bit-bit-code:

FileInputStream fis = new FileInputStream("sbs.dat");
byte[] file = new byte[4096];
m = Mac.getInstance("HmacSHA1");
int i=fis.read(file);
m.init(key);
while (i != -1)
{
    m.update(file);
    i=fis.read(file);
}
mac = m.doFinal();

And then all immediately fit:

File f = new File("sbs.dat");
long size = f.length();
byte[] file = new byte[(int) size];
fis.read(file);
m = Mac.getInstance("HmacSHA1");
m.init(key);
m.update(file);
mac = m.doFinal();

Don't they both produce the same hash?

. , while? ( , ..). , , , ...

: : -D. , ?

+5
3

. , fis.read(file) file.length . read() int, , .

:

m.init(key);
int i=fis.read(file);

while (i != -1)
{
    m.update(file, 0, i);
    i=fis.read(file);
}

Mac.update(byte [] data, int offset, int len), in byte [].

+5

read . , , read, .

+4

Just as Jason LeBrun says, the read method will not always read the specified number of bytes. For example: What do you think will happen if the file does not contain a multiplicity of 4096 bytes?

I would go for something like this:

        FileInputStream fis = new FileInputStream(filename);
        byte[] buffer = new byte[buffersize];
        Mac m = Mac.getInstance("HmacSHA1");
        m.init(key);

        int n;
        while ((n = fis.read(buffer)) != -1)
        {
            m.update(buffer, 0, n);
        }
        byte[] mac = m.doFinal();
+1
source

All Articles