下面列出了android.content.res.AssetFileDescriptor#getLength() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void findAPKFile(String filepath, Context context) {
String apkFilepath = getAPKFilepath(context);
// Get the offset and length for the file: theUrl, that is in your
// assets folder
AssetManager assetManager = context.getAssets();
try {
AssetFileDescriptor assFD = assetManager.openFd(filepath);
if (assFD != null) {
long offset = assFD.getStartOffset();
long fileSize = assFD.getLength();
assFD.close();
// **** offset and fileSize are the offset and size
// **** in bytes of the asset inside the APK
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public long getLength(Context context) throws PayloadNotFoundException {
AssetFileDescriptor afd = null;
long size = 0;
try {
afd = context.getResources().openRawResourceFd(data);
size = afd.getLength();
} catch (Resources.NotFoundException e) {
throw new ResourceNotFoundException(String.format("Resource id %d not found", data));
} finally {
if (afd != null) {
try {
afd.close();
} catch (IOException ignored) {
}
}
}
return size;
}
protected static long getAssetFileSize(String filename) {
AssetFileDescriptor assetFileDescriptor = null;
try {
assetFileDescriptor = InstrumentationRegistry.getInstrumentation().getContext().getAssets().openFd(filename);
return assetFileDescriptor.getLength();
} catch (IOException e) {
return -1;
} finally {
if (assetFileDescriptor != null) {
try {
assetFileDescriptor.close();
} catch (IOException ignored) {
}
}
}
}
@Override
protected int getLength(ImageRequest imageRequest) {
AssetFileDescriptor fd = null;
try {
fd = mResources.openRawResourceFd(getResourceId(imageRequest));
return (int) fd.getLength();
} catch (Resources.NotFoundException e) {
return -1;
} finally {
try {
if (fd != null) {
fd.close();
}
} catch (IOException ignored) {
// There's nothing we can do with the exception when closing descriptor.
}
}
}
/**
* {@inheritDoc}
*/
@Override
public long getLength(Uri uri) {
AssetFileDescriptor afd;
long result=super.getLength(uri);
try {
afd=getAssetFileDescriptor(uri);
result=afd.getLength();
afd.close();
}
catch (Exception e) {
Log.w(getClass().getSimpleName(), "Exception getting asset length", e);
}
return(result);
}
private int getLength(ImageRequest imageRequest) {
AssetFileDescriptor fd = null;
try {
fd = mResources.openRawResourceFd(getResourceId(imageRequest));
return (int) fd.getLength();
} catch (Resources.NotFoundException e) {
return -1;
} finally {
try {
if (fd != null) {
fd.close();
}
} catch (IOException ignored) {
// There's nothing we can do with the exception when closing descriptor.
}
}
}
private int getLength(ImageRequest imageRequest) {
AssetFileDescriptor fd = null;
try {
fd = mAssetManager.openFd(getAssetName(imageRequest));
return (int) fd.getLength();
} catch (IOException e) {
return -1;
} finally {
try {
if (fd != null) {
fd.close();
}
} catch (IOException ignored) {
// There's nothing we can do with the exception when closing descriptor.
}
}
}
private static AudioBuffer loadBuffer(AssetInfo assetInfo) throws IOException {
AndroidAssetInfo aai = (AndroidAssetInfo) assetInfo;
AssetFileDescriptor afd = null;
NativeVorbisFile file = null;
try {
afd = aai.openFileDescriptor();
int fd = afd.getParcelFileDescriptor().getFd();
file = new NativeVorbisFile(fd, afd.getStartOffset(), afd.getLength());
ByteBuffer data = BufferUtils.createByteBuffer(file.totalBytes);
file.readFully(data);
AudioBuffer ab = new AudioBuffer();
ab.setupFormat(file.channels, 16, file.sampleRate);
ab.updateData(data);
return ab;
} finally {
if (file != null) {
file.close();
}
if (afd != null) {
afd.close();
}
}
}
public static void copy(ContentResolver resolver, Uri source, Uri dest, OnCopyListener listener) throws IOException {
FileInputStream in = null;
OutputStream out = null;
try{
AssetFileDescriptor fd = resolver.openAssetFileDescriptor(source, "r");
in = fd != null ? fd.createInputStream() : null;
if (in == null){
throw new IOException("open the src file failed");
}
long total = fd.getLength();
long sum = 0;
out = resolver.openOutputStream(dest);
if (out == null) {
throw new IOException("open the dest file failed");
}
// Transfer bytes from in to out
byte[] buf = new byte[1024 * 4];
int len;
Thread thread = Thread.currentThread();
while ((len = in.read(buf)) > 0) {
if (thread.isInterrupted()) {
break;
}
sum += len;
out.write(buf, 0, len);
if (listener != null) {
listener.inProgress(sum * 1.0f / total);
}
}
}finally {
IOUtil.closeQuiet(in);
IOUtil.closeQuiet(out);
}
}
@Override public Result load(Request request, int networkPolicy) throws IOException {
String imagePath = request.uri.getPath().substring(1); // Grab only the path sans leading slash.
// Check the disk cache for the image. A non-null return value indicates a hit.
boolean cacheHit = emulatedDiskCache.get(imagePath) != null;
// If there's a hit, grab the image stream and return it.
if (cacheHit) {
return new Result(loadBitmap(imagePath), Picasso.LoadedFrom.DISK);
}
// If we are not allowed to hit the network and the cache missed return a big fat nothing.
if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
return null;
}
// If we got this far there was a cache miss and hitting the network is required. See if we need
// to fake an network error.
if (behavior.calculateIsFailure()) {
SystemClock.sleep(behavior.calculateDelay(MILLISECONDS));
throw new IOException("Fake network error!");
}
// We aren't throwing a network error so fake a round trip delay.
SystemClock.sleep(behavior.calculateDelay(MILLISECONDS));
// Since we cache missed put it in the LRU.
AssetFileDescriptor fileDescriptor = assetManager.openFd(imagePath);
long size = fileDescriptor.getLength();
fileDescriptor.close();
emulatedDiskCache.put(imagePath, size);
// Grab the image stream and return it.
return new Result(loadBitmap(imagePath), Picasso.LoadedFrom.NETWORK);
}
@Override
public long getLength() throws IOException {
if (length >= 0) {
return length;
}
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getResources().openRawResourceFd(drawableId);
length = fileDescriptor != null ? fileDescriptor.getLength() : 0;
} finally {
SketchUtils.close(fileDescriptor);
}
return length;
}
@CalledByNative
public static long[] open(String fileName) {
AssetFileDescriptor afd = null;
try {
AssetManager manager = ContextUtils.getApplicationContext().getAssets();
afd = manager.openNonAssetFd(fileName);
return new long[] {afd.getParcelFileDescriptor().detachFd(), afd.getStartOffset(),
afd.getLength()};
} catch (IOException e) {
// As a general rule there's no point logging here because the caller should handle
// receiving an fd of -1 sensibly, and the log message is either mirrored later, or
// unwanted (in the case where a missing file is expected), or wanted but will be
// ignored, as most non-fatal logs are.
// It makes sense to log here when the file exists, but is unable to be opened as an fd
// because (for example) it is unexpectedly compressed in an apk. In that case, the log
// message might save someone some time working out what has gone wrong.
// For that reason, we only suppress the message when the exception message doesn't look
// informative (Android framework passes the filename as the message on actual file not
// found, and the empty string also wouldn't give any useful information for debugging).
if (!e.getMessage().equals("") && !e.getMessage().equals(fileName)) {
Log.e(LOGTAG, "Error while loading asset " + fileName + ": " + e);
}
return new long[] {-1, -1, -1};
} finally {
try {
if (afd != null) {
afd.close();
}
} catch (IOException e2) {
Log.e(LOGTAG, "Unable to close AssetFileDescriptor", e2);
}
}
}
@CalledByNative
public static long[] open(String fileName) {
AssetFileDescriptor afd = null;
try {
AssetManager manager = ContextUtils.getApplicationContext().getAssets();
afd = manager.openNonAssetFd(fileName);
return new long[] {afd.getParcelFileDescriptor().detachFd(), afd.getStartOffset(),
afd.getLength()};
} catch (IOException e) {
// As a general rule there's no point logging here because the caller should handle
// receiving an fd of -1 sensibly, and the log message is either mirrored later, or
// unwanted (in the case where a missing file is expected), or wanted but will be
// ignored, as most non-fatal logs are.
// It makes sense to log here when the file exists, but is unable to be opened as an fd
// because (for example) it is unexpectedly compressed in an apk. In that case, the log
// message might save someone some time working out what has gone wrong.
// For that reason, we only suppress the message when the exception message doesn't look
// informative (Android framework passes the filename as the message on actual file not
// found, and the empty string also wouldn't give any useful information for debugging).
if (!e.getMessage().equals("") && !e.getMessage().equals(fileName)) {
Log.e(LOGTAG, "Error while loading asset " + fileName + ": " + e);
}
return new long[] {-1, -1, -1};
} finally {
try {
if (afd != null) {
afd.close();
}
} catch (IOException e2) {
Log.e(LOGTAG, "Unable to close AssetFileDescriptor", e2);
}
}
}
/**
* Creates drawable from AssetFileDescriptor.
* Convenience wrapper for {@link GifDrawable#GifDrawable(FileDescriptor)}
*
* @param afd source
* @throws NullPointerException if afd is null
* @throws IOException when opening failed
*/
public GifDrawable(AssetFileDescriptor afd) throws IOException {
if (afd == null)
throw new NullPointerException("Source is null");
FileDescriptor fd = afd.getFileDescriptor();
try {
mGifInfoPtr = openFd(mMetaData, fd, afd.getStartOffset(), false);
} catch (IOException ex) {
afd.close();
throw ex;
}
mColors = new int[mMetaData[0] * mMetaData[1]];
mInputSourceLength = afd.getLength();
}
@Override
public synchronized long getLength() throws IOException {
if (length >= 0) {
return length;
}
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getAssets().openFd(assetsFilePath);
length = fileDescriptor.getLength();
} finally {
SketchUtils.close(fileDescriptor);
}
return length;
}
@Override public Result load(Request request, int networkPolicy) throws IOException {
String imagePath = request.uri.getPath().substring(1); // Grab only the path sans leading slash.
// Check the disk cache for the image. A non-null return value indicates a hit.
boolean cacheHit = emulatedDiskCache.get(imagePath) != null;
// If there's a hit, grab the image stream and return it.
if (cacheHit) {
return new Result(loadBitmap(imagePath), Picasso.LoadedFrom.DISK);
}
// If we are not allowed to hit the network and the cache missed return a big fat nothing.
if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
return null;
}
// If we got this far there was a cache miss and hitting the network is required. See if we need
// to fake an network error.
if (behavior.calculateIsFailure()) {
SystemClock.sleep(behavior.calculateDelay(MILLISECONDS));
throw new IOException("Fake network error!");
}
// We aren't throwing a network error so fake a round trip delay.
SystemClock.sleep(behavior.calculateDelay(MILLISECONDS));
// Since we cache missed put it in the LRU.
AssetFileDescriptor fileDescriptor = assetManager.openFd(imagePath);
long size = fileDescriptor.getLength();
fileDescriptor.close();
emulatedDiskCache.put(imagePath, size);
// Grab the image stream and return it.
return new Result(loadBitmap(imagePath), Picasso.LoadedFrom.NETWORK);
}
@Override
public synchronized long getLength() throws IOException {
if (length >= 0) {
return length;
}
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(contentUri, "r");
length = fileDescriptor != null ? fileDescriptor.getLength() : 0;
} finally {
SketchUtils.close(fileDescriptor);
}
return length;
}
@Override
public long open(DataSpec dataSpec) throws ContentDataSourceException {
try {
Uri uri = dataSpec.uri;
this.uri = uri;
transferInitializing(dataSpec);
AssetFileDescriptor assetFileDescriptor = resolver.openAssetFileDescriptor(uri, "r");
this.assetFileDescriptor = assetFileDescriptor;
if (assetFileDescriptor == null) {
throw new FileNotFoundException("Could not open file descriptor for: " + uri);
}
FileInputStream inputStream = new FileInputStream(assetFileDescriptor.getFileDescriptor());
this.inputStream = inputStream;
long assetStartOffset = assetFileDescriptor.getStartOffset();
long skipped = inputStream.skip(assetStartOffset + dataSpec.position) - assetStartOffset;
if (skipped != dataSpec.position) {
// We expect the skip to be satisfied in full. If it isn't then we're probably trying to
// skip beyond the end of the data.
throw new EOFException();
}
if (dataSpec.length != C.LENGTH_UNSET) {
bytesRemaining = dataSpec.length;
} else {
long assetFileDescriptorLength = assetFileDescriptor.getLength();
if (assetFileDescriptorLength == AssetFileDescriptor.UNKNOWN_LENGTH) {
// The asset must extend to the end of the file. If FileInputStream.getChannel().size()
// returns 0 then the remaining length cannot be determined.
FileChannel channel = inputStream.getChannel();
long channelSize = channel.size();
bytesRemaining = channelSize == 0 ? C.LENGTH_UNSET : channelSize - channel.position();
} else {
bytesRemaining = assetFileDescriptorLength - skipped;
}
}
} catch (IOException e) {
throw new ContentDataSourceException(e);
}
opened = true;
transferStarted(dataSpec);
return bytesRemaining;
}
public void readFile(Uri inputFile)
throws java.io.FileNotFoundException,
java.io.IOException {
super.readFile(inputFile);
mNumFrames = 0;
mMaxFrames = 64; // This will grow as needed
mFrameGains = new int[mMaxFrames];
mMinGain = 1000000000;
mMaxGain = 0;
mBitRate = 10;
mOffset = 0;
InputStream stream = null;
AssetFileDescriptor file;
file = App.getInstance().getContentResolver().openAssetFileDescriptor(inputFile, "r");
if(file == null) throw new NullPointerException("File is null");
stream = file.createInputStream();
if(stream == null) throw new NullPointerException("Input stream is null");
else Log.d("audioSeekbar", "ReadFile: input stream is not null");
// No need to handle filesizes larger than can fit in a 32-bit int
mFileSize = (int) file.getLength();
if (mFileSize < 128) {
throw new java.io.IOException("File too small to parse");
}
byte[] header = new byte[12];
stream.read(header, 0, 6);
mOffset += 6;
if (header[0] == '#' &&
header[1] == '!' &&
header[2] == 'A' &&
header[3] == 'M' &&
header[4] == 'R' &&
header[5] == '\n') {
parseAMR(stream, mFileSize - 6);
}
stream.read(header, 6, 6);
mOffset += 6;
if (header[4] == 'f' &&
header[5] == 't' &&
header[6] == 'y' &&
header[7] == 'p' &&
header[8] == '3' &&
header[9] == 'g' &&
header[10] == 'p' &&
header[11] == '4') {
int boxLen =
((0xff & header[0]) << 24) |
((0xff & header[1]) << 16) |
((0xff & header[2]) << 8) |
((0xff & header[3]));
if (boxLen >= 4 && boxLen <= mFileSize - 8) {
stream.skip(boxLen - 12);
mOffset += boxLen - 12;
}
parse3gpp(stream, mFileSize - boxLen);
}
}
/**
* Loads the audio or video specified by mediaPath into the given
* MediaPlayer.
*
* @param mediaPlayer the MediaPlayer
* @param form the Form
* @param mediaPath the path to the media
*/
public static void loadMediaPlayer(MediaPlayer mediaPlayer, Form form, String mediaPath)
throws IOException {
MediaSource mediaSource = determineMediaSource(form, mediaPath);
switch (mediaSource) {
case ASSET:
AssetFileDescriptor afd = getAssetsIgnoreCaseAfd(form,mediaPath);
try {
FileDescriptor fd = afd.getFileDescriptor();
long offset = afd.getStartOffset();
long length = afd.getLength();
mediaPlayer.setDataSource(fd, offset, length);
} finally {
afd.close();
}
return;
case REPL_ASSET:
form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
mediaPlayer.setDataSource(replAssetPath(mediaPath));
return;
case SDCARD:
form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
mediaPlayer.setDataSource(mediaPath);
return;
case FILE_URL:
if (isExternalFileUrl(mediaPath)) {
form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
}
mediaPlayer.setDataSource(fileUrlToFilePath(mediaPath));
return;
case URL:
// This works both for streaming and non-streaming.
// TODO(halabelson): Think about whether we could get improved
// performance if we did buffering control.
mediaPlayer.setDataSource(mediaPath);
return;
case CONTENT_URI:
mediaPlayer.setDataSource(form, Uri.parse(mediaPath));
return;
case CONTACT_URI:
throw new IOException("Unable to load audio or video for contact " + mediaPath + ".");
}
throw new IOException("Unable to load audio or video " + mediaPath + ".");
}