1

i'm developing an app that needs to download, every some minutes, some files.

Using php, i list all the files and from java i get this list and check for file if is present or not. Once downloaded it, i need to check for integrity because sometimes after the download, some files are corrupted.

try{
    String path = ...
    URL url = new URL(path);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);         
    conn.setReadTimeout(30000);
    is = conn.getInputStream();
    ReadableByteChannel rbc = Channels.newChannel(is);
    FileOutputStream fos = null;
    fos = new FileOutputStream(local);
    fos.getChannel().transferFrom(rbc, 0, 1 << 24);
    fos.close();
    rbc.close();
} catch (FileNotFoundException e) {
    if(new File(local).exists()) new File(local).delete();
       return false;
} catch (IOException e) {
    if(new File(local).exists()) new File(local).delete();
       return false;
} catch (IOException e) {
    if(new File(local).exists()) new File(local).delete();
       return false;
}

return false;

What can i use in php and java to check for file integrity?

Jayyrus
  • 12,961
  • 41
  • 132
  • 214

1 Answers1

3

Maintain a checksum list on your server, download the file, generate a checksum of the downloaded file and check if it is the same as the one on the server. If it is, your file is fine.

Community
  • 1
  • 1
Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
  • ok for php, but for java i can't understand how can i use is = new DigestInputStream(is, md); – Jayyrus Apr 20 '13 at 08:55
  • otherwise, if i check the length of the file? is a faster method? – Jayyrus Apr 20 '13 at 08:59
  • @JackTurky A file may be corrupted and have the same length. Or it may be perfectly fine and have different lengths on the device and server due to filesystem and OS differences. Checksum is the most accurate. The code sample given is fairly simple. Make a file inputstream of your file, get a digestinputstream from it, read the file and then convert it to the MD5 checksum – Raghav Sood Apr 20 '13 at 09:01
  • ok, String md5 = DigestUtils.md5Hex(new FileInputStream(file)); and $md5 = md5_file($file); right? – Jayyrus Apr 20 '13 at 09:05
  • @JackTurky It requires reading in the entire file, so it will be slow. You could move it to a background thread or async task. – Raghav Sood Apr 20 '13 at 09:13