Example usage for java.io FileInputStream getFD

List of usage examples for java.io FileInputStream getFD

Introduction

In this page you can find the example usage for java.io FileInputStream getFD.

Prototype

public final FileDescriptor getFD() throws IOException 

Source Link

Document

Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.

Usage

From source file:com.soubw.other.WaveformFragment.java

protected synchronized void onPlay(int startPosition) {
    if (mIsPlaying) {
        handlePause();/*from w w w  . java 2  s.  c  om*/
        return;
    }

    if (mPlayer == null) {
        // Not initialized yet
        return;
    }

    try {
        mPlayStartMsec = mWaveformView.pixelsToMillisecs(startPosition);
        if (startPosition < mStartPos) {
            mPlayEndMsec = mWaveformView.pixelsToMillisecs(mStartPos);
        } else if (startPosition > mEndPos) {
            mPlayEndMsec = mWaveformView.pixelsToMillisecs(mMaxPos);
        } else {
            mPlayEndMsec = mWaveformView.pixelsToMillisecs(mEndPos);
        }

        mPlayStartOffset = 0;

        int startFrame = mWaveformView.secondsToFrames(mPlayStartMsec * 0.001);
        int endFrame = mWaveformView.secondsToFrames(mPlayEndMsec * 0.001);
        int startByte = mSoundFile.getSeekableFrameOffset(startFrame);
        int endByte = mSoundFile.getSeekableFrameOffset(endFrame);
        if (startByte >= 0 && endByte >= 0) {
            try {
                mPlayer.reset();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                FileInputStream subsetInputStream = new FileInputStream(mFile.getAbsolutePath());
                mPlayer.setDataSource(subsetInputStream.getFD(), startByte, endByte - startByte);
                mPlayer.prepare();
                mPlayStartOffset = mPlayStartMsec;
            } catch (Exception e) {
                Log.e(TAG, "Exception trying to play file subset", e);
                mPlayer.reset();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(mFile.getAbsolutePath());
                mPlayer.prepare();
                mPlayStartOffset = 0;
            }
        }

        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                handlePause();
            }
        });
        mIsPlaying = true;

        if (mPlayStartOffset == 0) {
            mPlayer.seekTo(mPlayStartMsec);
        }
        mPlayer.start();
        updateDisplay();
        enableDisableButtons();
    } catch (Exception e) {
        Log.e(TAG, "Exception while playing file", e);
    }
}

From source file:com.squalala.talkiewalkie.ui.activities.TalkActivity.java

private void playMp3(byte[] mp3SoundByteArray) {
    try {//from  ww w. j  a  v  a  2 s .com
        // create temp file that will hold byte array
        File tempMp3 = File.createTempFile("test", "m4a", getCacheDir());
        tempMp3.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(tempMp3);
        fos.write(mp3SoundByteArray);
        fos.close();

        // resetting mediaplayer instance to evade problems
        mediaPlayer.reset();
        // In case you run into issues with threading consider new instance like:
        // MediaPlayer mediaPlayer = new MediaPlayer();

        // Tried passing path directly, but kept getting
        // "Prepare failed.: status=0x1"
        // so using file descriptor instead
        FileInputStream fis = new FileInputStream(tempMp3);
        mediaPlayer.setDataSource(fis.getFD());

        mediaPlayer.prepare();
        mediaPlayer.start();
    } catch (IOException ex) {
        String s = ex.toString();
        ex.printStackTrace();
    }
}

From source file:com.squalala.talkiewalkie.ui.activities.TalkActivity.java

private void playAlert(byte[] mp3SoundByteArray) {

    if (session.isBeep()) {

        try {//from   w  w w .  j a  va 2  s.c  om
            // create temp file that will hold byte array
            File tempMp3 = File.createTempFile("test0", "m4a", getCacheDir());
            tempMp3.deleteOnExit();
            FileOutputStream fos = new FileOutputStream(tempMp3);
            fos.write(mp3SoundByteArray);
            fos.close();

            // resetting mediaplayer instance to evade problems
            mediaPlayerForBeep.reset();

            // In case you run into issues with threading consider new instance like:
            // MediaPlayer mediaPlayer = new MediaPlayer();

            // Tried passing path directly, but kept getting
            // "Prepare failed.: status=0x1"
            // so using file descriptor instead
            FileInputStream fis = new FileInputStream(tempMp3);
            mediaPlayerForBeep.setDataSource(fis.getFD());

            mediaPlayerForBeep.prepare();
            mediaPlayerForBeep.start();
        } catch (IOException ex) {
            String s = ex.toString();
            ex.printStackTrace();
        }
    }

}

From source file:org.apache.hadoop.hdfs.shortcircuit.ShortCircuitShm.java

/**
 * Create the ShortCircuitShm.//from   w w w .j a  va 2 s  .c o  m
 * 
 * @param shmId       The ID to use.
 * @param stream      The stream that we're going to use to create this 
 *                    shared memory segment.
 *                    
 *                    Although this is a FileInputStream, we are going to
 *                    assume that the underlying file descriptor is writable
 *                    as well as readable. It would be more appropriate to use
 *                    a RandomAccessFile here, but that class does not have
 *                    any public accessor which returns a FileDescriptor,
 *                    unlike FileInputStream.
 */
public ShortCircuitShm(ShmId shmId, FileInputStream stream) throws IOException {
    if (!NativeIO.isAvailable()) {
        throw new UnsupportedOperationException("NativeIO is not available.");
    }
    if (Shell.WINDOWS) {
        throw new UnsupportedOperationException("DfsClientShm is not yet implemented for Windows.");
    }
    if (unsafe == null) {
        throw new UnsupportedOperationException(
                "can't use DfsClientShm because we failed to " + "load misc.Unsafe.");
    }
    this.shmId = shmId;
    this.mmappedLength = getUsableLength(stream);
    this.baseAddress = POSIX.mmap(stream.getFD(), POSIX.MMAP_PROT_READ | POSIX.MMAP_PROT_WRITE, true,
            mmappedLength);
    this.slots = new Slot[mmappedLength / BYTES_PER_SLOT];
    this.allocatedSlots = new BitSet(slots.length);
    if (LOG.isTraceEnabled()) {
        LOG.trace("creating " + this.getClass().getSimpleName() + "(shmId=" + shmId + ", mmappedLength="
                + mmappedLength + ", baseAddress=" + String.format("%x", baseAddress) + ", slots.length="
                + slots.length + ")");
    }
}

From source file:com.xuwakao.mixture.framework.image.ImageFetcher.java

/**
 * The main process method, which will be called by the ImageWorker in the BitmapTask background
 * thread.//from  w  w  w. ja  va  2 s .  c  o m
 *
 * @param data The data to load the bitmap, in this case, a regular http URL
 * @return The downloaded and resized bitmap
 */
private Bitmap processBitmap(String data) {
    MLog.debug(TAG, "processBitmap - " + data);

    final String key = ImageCache.hashKeyForDisk(data);
    FileDescriptor fileDescriptor = null;
    FileInputStream fileInputStream = null;
    DiskLruCache.Snapshot snapshot;
    synchronized (mHttpDiskCacheLock) {
        // Wait for disk cache to initialize
        while (mHttpDiskCacheStarting) {
            try {
                mHttpDiskCacheLock.wait();
            } catch (InterruptedException e) {
            }
        }

        if (mHttpDiskCache != null) {
            try {
                snapshot = mHttpDiskCache.get(key);
                if (snapshot == null) {
                    MLog.debug(TAG, "processBitmap, not found in http cache, downloading...");
                    DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
                    if (editor != null) {
                        if (downloadUrlToStream(data, editor.newOutputStream(DISK_CACHE_INDEX))) {
                            editor.commit();
                        } else {
                            editor.abort();
                        }
                    }
                    snapshot = mHttpDiskCache.get(key);
                }
                if (snapshot != null) {
                    fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
                    fileDescriptor = fileInputStream.getFD();
                }
            } catch (IOException e) {
                MLog.error(TAG, "processBitmap - " + e);
            } catch (IllegalStateException e) {
                MLog.error(TAG, "processBitmap - " + e);
            } finally {
                if (fileDescriptor == null && fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    Bitmap bitmap = null;
    if (fileDescriptor != null) {
        bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight, getImageCache());
    }
    if (fileInputStream != null) {
        try {
            fileInputStream.close();
        } catch (IOException e) {
        }
    }
    return bitmap;
}

From source file:com.jcsoluciones.superdt.utilities.ImageFetcher.java

/**
 * The main process method, which will be called by the ImageWorker in the AsyncTask background
 * thread.//w w w .  j  av a2 s.c  o m
 *
 * @param data The data to load the bitmap, in this case, a regular http URL
 * @return The downloaded and resized bitmap
 */
private Bitmap processBitmap(String data) {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "processBitmap - " + data);
    }

    final String key = ImageCache.hashKeyForDisk(data);
    FileDescriptor fileDescriptor = null;
    FileInputStream fileInputStream = null;
    DiskLruCache.Snapshot snapshot;
    synchronized (mHttpDiskCacheLock) {
        // Wait for disk cache to initialize
        while (mHttpDiskCacheStarting) {
            try {
                mHttpDiskCacheLock.wait();
            } catch (InterruptedException e) {
            }
        }

        if (mHttpDiskCache != null) {
            try {
                snapshot = mHttpDiskCache.get(key);
                if (snapshot == null) {
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, "processBitmap, not found in http cache, downloading...");
                    }
                    DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
                    if (editor != null) {
                        if (downloadUrlToStream(data, editor.newOutputStream(DISK_CACHE_INDEX))) {
                            editor.commit();
                        } else {
                            editor.abort();
                        }
                    }
                    snapshot = mHttpDiskCache.get(key);
                }
                if (snapshot != null) {
                    fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
                    fileDescriptor = fileInputStream.getFD();
                }
            } catch (IOException e) {
                Log.e(TAG, "processBitmap - " + e);
            } catch (IllegalStateException e) {
                Log.e(TAG, "processBitmap - " + e);
            } finally {
                if (fileDescriptor == null && fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    Bitmap bitmap = null;
    if (fileDescriptor != null) {
        bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight, getImageCache());
    }
    if (fileInputStream != null) {
        try {
            fileInputStream.close();
        } catch (IOException e) {
        }
    }
    return bitmap;
}

From source file:com.inter.trade.ui.fragment.agent.AgentApplyFragmentNew.java

private void doPhoto(int requestCode, Intent data) {
    if (requestCode == SELECT_PIC_BY_PICK_PHOTO) // ??
    {// w w w.j av  a2  s.  c om
        if (data == null) {
            Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show();
            return;
        }
        photoUri = data.getData();
        if (photoUri == null) {
            Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show();
            return;
        }
    }
    String[] pojo = { MediaStore.Images.Media.DATA };
    mCursor = getActivity().managedQuery(photoUri, pojo, null, null, null);
    if (mCursor != null) {
        int columnIndex = mCursor.getColumnIndexOrThrow(pojo[0]);
        mCursor.moveToFirst();
        picPath = mCursor.getString(columnIndex);
        // cursor.close();
    }
    if (picPath != null && (picPath.endsWith(".png") || picPath.endsWith(".PNG") || picPath.endsWith(".jpg")
            || picPath.endsWith(".JPG"))) {
        try {
            File file = new File(picPath);
            FileInputStream inputStream = new FileInputStream(file);
            Logger.d("file", "length " + inputStream.available());
            //            inputStream.close();

            //         BitmapFactory.Options options = new BitmapFactory.Options();
            //         options.inSampleSize = 4;
            //         Bitmap bm = BitmapFactory.decodeFile(picPath, options);
            Bitmap bm = decodeSampledBitmapFromDescriptor(inputStream.getFD(), 300, 300, null);
            if (pos == 0) {
                agent_applying_license_photo_img.setBackgroundDrawable(null);
                agent_applying_license_photo_img.setImageBitmap(bm);
                identityBitmap1 = Bitmap.createScaledBitmap(bm, 200, 300, true);
                path[0] = picPath;
                mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1");
                //            agent_applying_license_photo_done_img.setVisibility(View.VISIBLE);
            } else if (pos == 1) {
                agent_applying_organization_photo_img.setBackgroundDrawable(null);
                agent_applying_organization_photo_img.setImageBitmap(bm);
                identityBitmap2 = Bitmap.createScaledBitmap(bm, 200, 300, true);
                path[1] = picPath;
                mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1");
                //            agent_applying_organization_photo_done_img.setVisibility(View.VISIBLE);
            } else if (pos == 2) {
                agent_applying_tax_photo_img.setBackgroundDrawable(null);
                agent_applying_tax_photo_img.setImageBitmap(bm);
                identityBitmap3 = Bitmap.createScaledBitmap(bm, 200, 300, true);
                path[2] = picPath;
                mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1");
                //            agent_applying_tax_photo_done_img.setVisibility(View.VISIBLE);
            } else if (pos == 3) {
                agent_applying_id_card_photo_img.setBackgroundDrawable(null);
                agent_applying_id_card_photo_img.setImageBitmap(bm);
                identityBitmap4 = Bitmap.createScaledBitmap(bm, 200, 300, true);
                path[3] = picPath;
                mInfoList.get(agentType).infoDataList.get(pos).putValue("selectpic", "1");
                //            agent_applying_id_card_photo_done_img.setVisibility(View.VISIBLE);
            }
            isPicChange = true;
            //         agent_applying_license_photo_done_img.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            // TODO: handle exception
        }
    } else {
        Toast.makeText(getActivity(), "?", Toast.LENGTH_LONG).show();
    }
}

From source file:com.tangjd.displayingbitmaps.util.ImageFetcher.java

/**
 * The main process method, which will be called by the ImageWorker in the AsyncTask background
 * thread.// w w  w.j a  v a 2  s  . c  o m
 *
 * @param url The url to load the bitmap, in this case, a regular http URL
 * @return The downloaded and resized bitmap
 */
private Bitmap processBitmap(String url) {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "processBitmap - " + url);
    }

    final String key = ImageCache.hashKeyForDisk(url);
    FileDescriptor fileDescriptor = null;
    FileInputStream fileInputStream = null;
    DiskLruCache.Snapshot snapshot;
    synchronized (mHttpDiskCacheLock) {
        // Wait for disk cache to initialize
        while (mHttpDiskCacheStarting) {
            try {
                mHttpDiskCacheLock.wait();
            } catch (InterruptedException e) {
            }
        }

        if (mHttpDiskCache != null) {
            try {
                snapshot = mHttpDiskCache.get(key);
                if (snapshot == null) {
                    Log.e(TAG, "doInBackground - not found in http cache, downloading...");
                    DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
                    if (editor != null) {
                        if (downloadUrlToStream(url, editor.newOutputStream(DISK_CACHE_INDEX))) {
                            editor.commit();
                        } else {
                            editor.abort();
                        }
                    }
                    snapshot = mHttpDiskCache.get(key);
                } else {
                    Log.e(TAG, "doInBackground - http disk cache hit");
                }
                if (snapshot != null) {
                    fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
                    fileDescriptor = fileInputStream.getFD();
                }
            } catch (IOException e) {
                Log.e(TAG, "processBitmap - " + e);
            } catch (IllegalStateException e) {
                Log.e(TAG, "processBitmap - " + e);
            } finally {
                if (fileDescriptor == null && fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }

    Bitmap bitmap = null;
    if (fileDescriptor != null) {
        bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight, getImageCache());
    }
    if (fileInputStream != null) {
        try {
            fileInputStream.close();
        } catch (IOException e) {
        }
    }
    return bitmap;
}

From source file:com.ifeng.util.imagecache.ImageFetcher.java

/**
 * The main process method, which will be called by the ImageWorker in the
 * AsyncTask background thread./*from  w w  w. ja  v  a2  s.  c  om*/
 * 
 * @param taskItem
 *            The data to load the bitmap, in this case, a regular item
 *            contain http URL
 * @param processCallback
 * 
 * @return The downloaded and resized bitmap
 */
private Bitmap processBitmapInternal(RemoteBitmapTaskItem taskItem, OnProcessProgressUpdate processCallback) {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "processBitmap - " + taskItem.mDataSource);
    }

    String url = (String) taskItem.mDataSource;
    final String key = ImageCache.hashKeyForDisk(url);
    FileDescriptor fileDescriptor = null;
    FileInputStream fileInputStream = null;
    DiskLruCache.Snapshot snapshot;
    synchronized (mHttpDiskCacheLock) {
        // Wait for disk cache to initialize
        while (mHttpDiskCacheStarting) {
            try {
                mHttpDiskCacheLock.wait();
            } catch (InterruptedException e) {
            }
        }
    }

    // editor???DiskLruCache??
    DiskLruCache.Editor editor = null;
    if (mHttpDiskCache != null) {
        try {
            snapshot = mHttpDiskCache.get(key);
            if (snapshot == null) {
                if (BuildConfig.DEBUG) {
                    Log.d(TAG, "processBitmap, not found in http cache, downloading...");
                }
                editor = mHttpDiskCache.edit(key);
                if (editor != null) {
                    if (downloadUrlToStream(url, editor.newOutputStream(DISK_CACHE_INDEX), processCallback)) {
                        editor.commit();
                    } else {
                        editor.abort();
                    }
                }
                snapshot = mHttpDiskCache.get(key);
            }
            if (snapshot != null) {
                fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
                fileDescriptor = fileInputStream.getFD();
            }
        } catch (IOException e) {
            Log.e(TAG, "processBitmap - " + e);
        } catch (IllegalStateException e) {
            Log.e(TAG, "processBitmap - " + e);
        } finally {
            if (fileDescriptor == null && fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }

    Bitmap bitmap = null;
    if (fileDescriptor != null) {
        bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, taskItem.mImageSize, taskItem.mImageSize,
                getImageCache());
    }

    if (fileInputStream != null) {
        try {
            fileInputStream.close();
        } catch (IOException e) {
        }
    }

    if (editor != null) {
        // ?DiskLruCache
        synchronized (editor) {
            editor.notify();
        }
    }

    return bitmap;
}

From source file:com.itsherpa.andg.imageloader.ImageFetcher.java

/**
 * The main process method, which will be called by the ImageWorker in the
 * AsyncTask background thread.//from w w w  . ja  va 2  s  .  com
 * 
 * @param data
 *            The data to load the bitmap, in this case, a regular http URL
 * @return The downloaded and resized bitmap
 */
private Bitmap processBitmap(String data, int width, int height, String urlCache) {
    // if (BuildConfig.DEBUG) {
    // LogUtils.d(TAG, "processBitmap - " + data);
    // }

    final String key = ImageCache.hashKeyForDisk(urlCache);
    FileDescriptor fileDescriptor = null;
    FileInputStream fileInputStream = null;
    DiskLruCache.Snapshot snapshot;
    synchronized (mHttpDiskCacheLock) {
        // Wait for disk cache to initialize
        while (mHttpDiskCacheStarting) {
            try {
                mHttpDiskCacheLock.wait();
            } catch (InterruptedException e) {
            }
        }

        if (mHttpDiskCache != null) {
            try {
                snapshot = mHttpDiskCache.get(key);
                if (snapshot == null) {
                    LogUtils.d(TAG, "processBitmap, not found in http cache, downloading...");
                    DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
                    if (editor != null) {
                        if (downloadUrlToStream2(data, editor.newOutputStream(DISK_CACHE_INDEX))) {
                            editor.commit();
                        } else {
                            editor.abort();
                        }
                    }
                    snapshot = mHttpDiskCache.get(key);
                }
                if (snapshot != null) {
                    // if (BuildConfig.DEBUG) {
                    // LogUtils.d(TAG, HTTP_CACHE_DIR + " cache hit");
                    // }
                    fileInputStream = (FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
                    fileDescriptor = fileInputStream.getFD();
                }
            } catch (IOException e) {
                LogUtils.e(TAG, "processBitmap - " + e);
            } catch (IllegalStateException e) {
                LogUtils.e(TAG, "processBitmap - " + e);
            } finally {
                if (fileDescriptor == null && fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }
    Bitmap bitmap = null;
    if (fileDescriptor != null) {
        bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, width, height, getImageCache());
    }
    if (fileInputStream != null) {
        try {
            fileInputStream.close();
        } catch (IOException e) {
        }
    }
    return bitmap;
}