Beispiel #1
0
        static long CopyFileStream(FileInputStream @is, FileOutputStream os)
        {
            FileChannel srcChannel  = null;
            FileChannel destChannel = null;
            long        length;

            try
            {
                srcChannel  = @is.Channel;
                destChannel = os.Channel;
                length      = srcChannel.TransferTo(0L, srcChannel.Size(), destChannel);
            }
            finally
            {
                if (srcChannel != null)
                {
                    srcChannel.Close();
                }
                if (destChannel != null)
                {
                    destChannel.Close();
                }
            }
            return(length);
        }
Beispiel #2
0
        /// <summary>
        /// Transfers data from FileChannel using
        /// <see cref="FileChannel.TransferTo(long, long, WritableByteChannel)
        ///     "/>
        /// .
        /// Updates <code>waitForWritableTime</code> and <code>transferToTime</code>
        /// with the time spent blocked on the network and the time spent transferring
        /// data from disk to network respectively.
        /// Similar to readFully(), this waits till requested amount of
        /// data is transfered.
        /// </summary>
        /// <param name="fileCh">FileChannel to transfer data from.</param>
        /// <param name="position">position within the channel where the transfer begins</param>
        /// <param name="count">number of bytes to transfer.</param>
        /// <param name="waitForWritableTime">
        /// nanoseconds spent waiting for the socket
        /// to become writable
        /// </param>
        /// <param name="transferTime">nanoseconds spent transferring data</param>
        /// <exception cref="System.IO.EOFException">
        ///
        /// If end of input file is reached before requested number of
        /// bytes are transfered.
        /// </exception>
        /// <exception cref="SocketTimeoutException">
        ///
        /// If this channel blocks transfer longer than timeout for
        /// this stream.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// Includes any exception thrown by
        /// <see cref="FileChannel.TransferTo(long, long, WritableByteChannel)
        ///     "/>
        /// .
        /// </exception>
        public virtual void TransferToFully(FileChannel fileCh, long position, int count,
                                            LongWritable waitForWritableTime, LongWritable transferToTime)
        {
            long waitTime     = 0;
            long transferTime = 0;

            while (count > 0)
            {
                /*
                 * Ideally we should wait after transferTo returns 0. But because of
                 * a bug in JRE on Linux (http://bugs.sun.com/view_bug.do?bug_id=5103988),
                 * which throws an exception instead of returning 0, we wait for the
                 * channel to be writable before writing to it. If you ever see
                 * IOException with message "Resource temporarily unavailable"
                 * thrown here, please let us know.
                 *
                 * Once we move to JAVA SE 7, wait should be moved to correct place.
                 */
                long start = Runtime.NanoTime();
                WaitForWritable();
                long wait        = Runtime.NanoTime();
                int  nTransfered = (int)fileCh.TransferTo(position, count, GetChannel());
                if (nTransfered == 0)
                {
                    //check if end of file is reached.
                    if (position >= fileCh.Size())
                    {
                        throw new EOFException("EOF Reached. file size is " + fileCh.Size() + " and " + count
                                               + " more bytes left to be " + "transfered.");
                    }
                }
                else
                {
                    //otherwise assume the socket is full.
                    //waitForWritable(); // see comment above.
                    if (nTransfered < 0)
                    {
                        throw new IOException("Unexpected return of " + nTransfered + " from transferTo()"
                                              );
                    }
                    else
                    {
                        position += nTransfered;
                        count    -= nTransfered;
                    }
                }
                long transfer = Runtime.NanoTime();
                waitTime     += wait - start;
                transferTime += transfer - wait;
            }
            if (waitForWritableTime != null)
            {
                waitForWritableTime.Set(waitTime);
            }
            if (transferToTime != null)
            {
                transferToTime.Set(transferTime);
            }
        }
Beispiel #3
0
        /**
         * 文件拷贝
         *
         * @param src  源文件
         * @param desc 目的文件
         */
        public static void fileChannelCopy(File src, File desc)
        {
            //createFile(src);
            createFile(desc);
            FileInputStream  fi = null;
            FileOutputStream fo = null;

            try
            {
                fi = new FileInputStream(src);
                fo = new FileOutputStream(desc);
                FileChannel inStream  = fi.Channel;                 //得到对应的文件通道
                FileChannel outStream = fo.Channel;                 //得到对应的文件通道
                inStream.TransferTo(0, inStream.Size(), outStream); //连接两个通道,并且从in通道读取,然后写入out通道
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
            }
            finally
            {
                try
                {
                    if (fo != null)
                    {
                        fo.Close();
                    }
                    if (fi != null)
                    {
                        fi.Close();
                    }
                }
                catch (IOException e)
                {
                    e.PrintStackTrace();
                }
            }
        }
Beispiel #4
0
 /// <summary>
 /// Unbuffered file copy from src to dst without tainting OS buffer cache
 /// In POSIX platform:
 /// It uses FileChannel#transferTo() which internally attempts
 /// unbuffered IO on OS with native sendfile64() support and falls back to
 /// buffered IO otherwise.
 /// </summary>
 /// <remarks>
 /// Unbuffered file copy from src to dst without tainting OS buffer cache
 /// In POSIX platform:
 /// It uses FileChannel#transferTo() which internally attempts
 /// unbuffered IO on OS with native sendfile64() support and falls back to
 /// buffered IO otherwise.
 /// It minimizes the number of FileChannel#transferTo call by passing the the
 /// src file size directly instead of a smaller size as the 3rd parameter.
 /// This saves the number of sendfile64() system call when native sendfile64()
 /// is supported. In the two fall back cases where sendfile is not supported,
 /// FileChannle#transferTo already has its own batching of size 8 MB and 8 KB,
 /// respectively.
 /// In Windows Platform:
 /// It uses its own native wrapper of CopyFileEx with COPY_FILE_NO_BUFFERING
 /// flag, which is supported on Windows Server 2008 and above.
 /// Ideally, we should use FileChannel#transferTo() across both POSIX and Windows
 /// platform. Unfortunately, the wrapper(Java_sun_nio_ch_FileChannelImpl_transferTo0)
 /// used by FileChannel#transferTo for unbuffered IO is not implemented on Windows.
 /// Based on OpenJDK 6/7/8 source code, Java_sun_nio_ch_FileChannelImpl_transferTo0
 /// on Windows simply returns IOS_UNSUPPORTED.
 /// Note: This simple native wrapper does minimal parameter checking before copy and
 /// consistency check (e.g., size) after copy.
 /// It is recommended to use wrapper function like
 /// the Storage#nativeCopyFileUnbuffered() function in hadoop-hdfs with pre/post copy
 /// checks.
 /// </remarks>
 /// <param name="src">The source path</param>
 /// <param name="dst">The destination path</param>
 /// <exception cref="System.IO.IOException"/>
 public static void CopyFileUnbuffered(FilePath src, FilePath dst)
 {
     if (nativeLoaded && Shell.Windows)
     {
         CopyFileUnbuffered0(src.GetAbsolutePath(), dst.GetAbsolutePath());
     }
     else
     {
         FileInputStream  fis    = null;
         FileOutputStream fos    = null;
         FileChannel      input  = null;
         FileChannel      output = null;
         try
         {
             fis    = new FileInputStream(src);
             fos    = new FileOutputStream(dst);
             input  = fis.GetChannel();
             output = fos.GetChannel();
             long remaining   = input.Size();
             long position    = 0;
             long transferred = 0;
             while (remaining > 0)
             {
                 transferred = input.TransferTo(position, remaining, output);
                 remaining  -= transferred;
                 position   += transferred;
             }
         }
         finally
         {
             IOUtils.Cleanup(Log, output);
             IOUtils.Cleanup(Log, fos);
             IOUtils.Cleanup(Log, input);
             IOUtils.Cleanup(Log, fis);
         }
     }
 }
Beispiel #5
0
        private void CopyFileToDownloads(Android.Net.Uri croppedFileUri)
        {
            try
            {
                String downloadsDirectoryPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
                String filename = String.Format("%d_%s", Calendar.Instance.TimeInMillis, croppedFileUri.LastPathSegment);

                Java.IO.File saveFile = new Java.IO.File(downloadsDirectoryPath, filename);

                FileInputStream  inStream   = new FileInputStream(new Java.IO.File(croppedFileUri.Path));
                FileOutputStream outStream  = new FileOutputStream(saveFile);
                FileChannel      inChannel  = inStream.Channel;
                FileChannel      outChannel = outStream.Channel;
                inChannel.TransferTo(0, inChannel.Size(), outChannel);
                inStream.Close();
                outStream.Close();

                ShowNotification(saveFile);
            }
            catch (Exception e)
            {
                Toast.MakeText(this, e.Message, ToastLength.Short).Show();
            }
        }