Returns the length in bytes of a given file object.
    Necessary because os.fstat only works on real files and not file-like
    objects. This works on more types of streams, primarily StringIO.
762509
def file_length(file_obj):
    
    file_obj.seek(0, 2)
    length = file_obj.tell()
    file_obj.seek(0)
    return length
1167819
def _GetDecodedStreamSize(self):
    
    self._file_object.seek(0, os.SEEK_SET)

    self._decoder = self._GetDecoder()
    self._decoded_data = b''

    encoded_data_offset = 0
    encoded_data_size = self._file_object.get_size()
    decoded_stream_size = 0

    while encoded_data_offset < encoded_data_size:
      read_count = self._ReadEncodedData(self._ENCODED_DATA_BUFFER_SIZE)
      if read_count == 0:
        break

      encoded_data_offset += read_count
      decoded_stream_size += self._decoded_data_size

    return decoded_stream_size
85835
public long getTransferSize() throws SftpStatusException, SshException {

		Object obj;
		long size = 0;
		SftpFile sftpfile;
		File file;
		for (Enumeration e = newFiles.elements(); e.hasMoreElements();) {
			obj = e.nextElement();
			if (obj instanceof File) {
				file = (File) obj;
				if (file.isFile()) {
					size += file.length();
				}
			} else if (obj instanceof SftpFile) {
				sftpfile = (SftpFile) obj;
				if (sftpfile.isFile()) {
					size += sftpfile.getAttributes().getSize().longValue();
				}
			}
		}
		for (Enumeration e = updatedFiles.elements(); e.hasMoreElements();) {
			obj = e.nextElement();

			if (obj instanceof File) {
				file = (File) obj;
				if (file.isFile()) {
					size += file.length();
				}
			} else if (obj instanceof SftpFile) {
				sftpfile = (SftpFile) obj;
				if (sftpfile.isFile()) {
					size += sftpfile.getAttributes().getSize().longValue();
				}
			}
		}

		// Add a value for deleted files??

		return size;
	}
1045511
def read_lengths_file( name ):
    

    chrom_to_length = {}
    f = file ( name, "rt" )
    for line in f:
        line = line.strip()
        if line == '' or line[0] == '#': continue
        try:
            fields = line.split()
            if len(fields) != 2: raise
            chrom = fields[0]
            length = int( fields[1] )
        except:
            raise ValueError("bad length file line: %s" % line)
        if chrom in chrom_to_length and length != chrom_to_length[chrom]:
            raise ValueError("%s has more than one length!" % chrom)
        chrom_to_length[chrom] = length
    f.close()
    return chrom_to_length
1301429
def safe_size(source):
    

    if source is None:
        return None

    total_bytes = 0
    bytes = []
    b = source.read(MIN_READ_SIZE)
    while b:
        total_bytes += len(b)
        bytes.append(b)
        if total_bytes > MAX_STRING_SIZE:
            try:
                data = FileString(TemporaryFile())
                for bb in bytes:
                    data.write(bb)
                del bytes
                del bb
                b = source.read(MIN_READ_SIZE)
                while b:
                    total_bytes += len(b)
                    data.write(b)
                    b = source.read(MIN_READ_SIZE)
                data.seek(0)
                Log.note("Using file of size {{length}} instead of str()",  length= total_bytes)

                return data
            except Exception as e:
                Log.error("Could not write file > {{num}} bytes",  num= total_bytes, cause=e)
        b = source.read(MIN_READ_SIZE)

    data = b"".join(bytes)
    del bytes
    return data
186564
def getsize(o_file):
    
    startpos = o_file.tell()
    o_file.seek(0)
    o_file.seek(0, SEEK_END)
    size = o_file.tell()
    o_file.seek(startpos)
    return size
8616
def get_size(self):
    
    if not self._is_open:
      raise IOError('Not opened.')

    if not hasattr(self._file_object, 'get_size'):
      if not self._size:
        current_offset = self.get_offset()
        self.seek(0, os.SEEK_END)
        self._size = self.get_offset()
        self.seek(current_offset, os.SEEK_SET)
      return self._size

    return self._file_object.get_size()
883518
public static long getFileLength(final File file) throws FileNotFoundException {
        try {
            return AccessController.doPrivileged(
                                                 new PrivilegedExceptionAction<Long>() {
                                                     @Override
                                                     public Long run() throws FileNotFoundException {
                                                         return file.length();
                                                     }
                                                 });
        } catch (PrivilegedActionException e) {
            // Creating a FileOutputStream can only return a FileNotFoundException
            throw (FileNotFoundException) e.getCause();
        }
    }
1089162
def size(self, filename: str) -> int:
        '''
        '''
        yield from self._control_stream.write_command(Command('SIZE', filename))

        reply = yield from self._control_stream.read_reply()

        self.raise_if_not_match('File size', ReplyCodes.file_status, reply)

        try:
            return int(reply.text.strip())
        except ValueError:
            return
923893
@Override
    public long getContentSize(Context ctx) throws StreamIOException {
        try {
            // For new or modified datastreams, the new bytestream hasn't yet been
            // committed. However, we need to access it in order to compute
            // the datastream checksum
            if (DSLocation.startsWith(UPLOADED_SCHEME)) {
                // TODO: refactor to use proper temp file management - FCREPO-718
                // for now, just get the file directly (see also DefaultManagement.getTempStream(...))
                String internalId = DSLocation.substring(UPLOADED_SCHEME.length());
                File uploadedFile = new File(getTempUploadDir(), internalId);
                // check it has not been automatically purged (see DefaultManagement.purgeUploadedFiles())
                if (uploadedFile.exists()) {
                    return uploadedFile.length();
                } else {
                    throw new StreamIOException("Uploaded file " + DSLocation + " no longer exists.");
                }

            } else if (DSLocation.startsWith(TEMP_SCHEME)) {
                // TODO: refactor to use proper temp file management - FCREPO-718
                String fileName = DSLocation.substring(TEMP_SCHEME.length());
                File tempFile = new File(fileName);
                // check it has not been removed elsewhere (should not happen)
                if (tempFile.exists()) {
                    return tempFile.length();
                } else {
                    throw new StreamIOException("Temp file " + DSLocation + " no longer exists.");
                }
            } else if (Datastream.DS_LOCATION_TYPE_INTERNAL.equals(DSLocationType)) {
                ILowlevelStorage llstore = getLLStore();
                if (s_llsizable) {
                    return ((ISizable)llstore).getDatastreamSize(DSLocation);
                } else {
                    return 0;
                }
            } else if (Datastream.DS_LOCATION_TYPE_URL.equals(DSLocationType)) {
                // Managed content can have URL dsLocation on ingest
                ValidationUtility.validateURL(DSLocation, this.DSControlGrp);
                // If validation has succeeded, assume an external resource.
                // Fetch it, store it locally, update DSLocation
                if (ctx == null) {
                    ctx = ReadOnlyContext.getContext(null, null, "", false);
                    // changed from below, which sets noOp to true, seems to cause an AuthZ permitted exception
                    // in PolicyEnforcementPoint.enforce(...)
                    // ctx = ReadOnlyContext.EMPTY;
                }
               ContentManagerParams params = new ContentManagerParams(DSLocation);
                params.setContext(ctx);
                MIMETypedStream stream = getExternalContentManager()
                        .getExternalContent(params);

                // TODO: refactor temp file management - see FCREPO-718; for now create temp file and write to it
                // note - don't use temp upload directory, use (container's) temp dir (upload dir is for uploads)
                File tempFile = File.createTempFile("managedcontentupdate", null);
                OutputStream os = new FileOutputStream(tempFile);
                StreamUtility.pipeStream(stream.getStream(), os, 32768);
                DSLocation = TEMP_SCHEME + tempFile.getAbsolutePath();
                return tempFile.length();
            }
        } catch (Throwable th) {
            throw new StreamIOException("[DatastreamManagedContent] returned "
                    + " the error: \"" + th.getClass().getName()
                    + "\". Reason: " + th.getMessage(), th);
        }
        throw new StreamIOException("[DatastreamManagedContent] could not resolve dsLocation " + DSLocation + " dsLocationType " + DSLocationType);
    }
905589
static int getLength(int lenByte, InputStream in) throws IOException {
        int value, tmp;

        tmp = lenByte;
        if ((tmp & 0x080) == 0x00) { // short form, 1 byte datum
            value = tmp;
        } else {                     // long form or indefinite
            tmp &= 0x07f;

            /*
             * NOTE:  tmp == 0 indicates indefinite length encoded data.
             * tmp > 4 indicates more than 4Gb of data.
             */
            if (tmp == 0)
                return -1;
            if (tmp < 0 || tmp > 4)
                throw new IOException("DerInputStream.getLength(): lengthTag="
                    + tmp + ", "
                    + ((tmp < 0) ? "incorrect DER encoding." : "too big."));

            for (value = 0; tmp > 0; tmp --) {
                value <<= 8;
                value += 0x0ff & in.read();
            }
            if (value < 0) {
                throw new IOException("DerInputStream.getLength(): "
                        + "Invalid length bytes");
            }
        }
        return value;
    }
1318144
def get_value_length(byte):
    
    length_value = byte & length_type_mask
    return LengthTypes.to_ints.get(length_value, byte & length_mask)
12745
def get_byte_length(self, decoded=True) -> int:
        
        end = len(self.decoded_bits) if decoded else len(self.__plain_bits)
        end = self.convert_index(end, 0, 2, decoded=decoded)[0]
        return int(end)
534311
def _file_not_empty(tmpfile):
        
        if os.path.exists(tmpfile):
            return os.stat(tmpfile).st_size != 0
        else:
            return False
93865
def file_size(filename):
    '''
    
    '''
    # Using open/lseek works on both regular files and block devices
    fd = os.open(filename, os.O_RDONLY)
    try:
        return os.lseek(fd, 0, os.SEEK_END)
    except KeyboardInterrupt as e:
        raise e
    except Exception as e:
        raise Exception(
            "file_size failed to obtain the size of '%s': %s" % (filename, str(e)))
    finally:
        os.close(fd)
1210206
private int readerLength(File file, InputStreamReader isr)
	{
		String name = file.getName();

		if (name.endsWith(".docx"))
		{
			return ((DocxStreamReader) isr).length();
		} else if (name.endsWith(".odt"))
		{
			return ((ODFStreamReader) isr).length();
		} else
		{
			return (int) (file.length() + 1);
		}
	}
571756
def _GetStat(self):
    
    stat_object = super(SQLiteBlobFileEntry, self)._GetStat()

    if not self._is_virtual:
      file_object = self.GetFileObject()
      if not file_object:
        raise errors.BackEndError(
            'Unable to retrieve SQLite blob file-like object.')

      try:
        stat_object.size = file_object.get_size()
      finally:
        file_object.close()

    return stat_object