private boolean isDownloadedFileOk(@NonNull File file){
  try {
    long length=file.length();
    if (length < 1024) {
      Log.e(TAG,file + " is too small to be an audio file");
      return false;
    }
 else     if (length < 5 * 1024 * 1024) {
      RandomAccessFile randomAccessFile=new RandomAccessFile(file,"r");
      for (long offset=0; offset < length; offset++) {
        randomAccessFile.seek(offset);
        char firstChar=(char)randomAccessFile.readByte();
        if (!Character.isWhitespace(firstChar)) {
          if (firstChar == '<') {
            break;
          }
 else {
            return true;
          }
        }
      }
      for (long offset=length - 1; offset >= 0; offset--) {
        randomAccessFile.seek(offset);
        char lastChar=(char)randomAccessFile.readByte();
        if (!Character.isWhitespace(lastChar)) {
          if (lastChar == '>') {
            Log.e(TAG,file + ": XML/HTML downloaded instead of audio");
            return false;
          }
 else {
            return true;
          }
        }
      }
      Log.e(TAG,file + " consists of whitespaces only");
      return false;
    }
 else {
      return true;
    }
  }
 catch (  IOException exception) {
    Log.e(TAG,"Error while checking downloaded file",exception);
    return false;
  }
}

private boolean isDownloadedFileOk ( @ NonNull File file ) { try { long length = file . length ( ) ; if ( length < 1024 ) { Log . e ( TAG , file + " is too small to be an audio file" ) ; return false ; } else if ( length < 5 * 1024 * 1024 ) { RandomAccessFile randomAccessFile = new RandomAccessFile ( file , "r" ) ; for ( long offset = 0 ; offset < length ; offset ++ ) { randomAccessFile . seek ( offset ) ; char firstChar = ( char ) randomAccessFile . readByte ( ) ; if ( ! Character . isWhitespace ( firstChar ) ) { if ( firstChar == '<' ) { break ; } else { return true ; } } } for ( long offset = length - 1 ; offset >= 0 ; offset -- ) { randomAccessFile . seek ( offset ) ; char lastChar = ( char ) randomAccessFile . readByte ( ) ; if ( ! Character . isWhitespace ( lastChar ) ) { if ( lastChar == '>' ) { Log . e ( TAG , file + ": XML/HTML downloaded instead of audio" ) ; return false ; } else { return true ; } } } Log . e ( TAG , file + " consists of whitespaces only" ) ; return false ; } else { return true ; } } catch ( IOException exception ) { Log . e ( TAG , "Error while checking downloaded file" , exception ) ; return false ; } }
sometimes body of redirect response is downloaded instead of media file ( seen this on xperia z2 with moscow metro wifi ) . such body could be empty or could contain some html code . if downloaded file size is less then 1kb , consider it is an error . if file size is between 1kb and 5mb , check if it starts with < and ends with > ( which means it ' s html / xml ) .
