Example usage for java.nio.channels FileChannel close

List of usage examples for java.nio.channels FileChannel close

Introduction

In this page you can find the example usage for java.nio.channels FileChannel close.

Prototype

public final void close() throws IOException 

Source Link

Document

Closes this channel.

Usage

From source file:com.liferay.portal.util.FileImpl.java

public boolean isSameContent(File file, byte[] bytes, int length) {
    FileChannel fileChannel = null;

    try {//from  w  w  w  .  j a  v  a  2s .c  om
        FileInputStream fileInputStream = new FileInputStream(file);

        fileChannel = fileInputStream.getChannel();

        if (fileChannel.size() != length) {
            return false;
        }

        byte[] buffer = new byte[1024];

        ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);

        int bufferIndex = 0;
        int bufferLength = -1;

        while (((bufferLength = fileChannel.read(byteBuffer)) > 0) && (bufferIndex < length)) {

            for (int i = 0; i < bufferLength; i++) {
                if (buffer[i] != bytes[bufferIndex++]) {
                    return false;
                }
            }

            byteBuffer.clear();
        }

        if ((bufferIndex != length) || (bufferLength != -1)) {
            return false;
        } else {
            return true;
        }
    } catch (Exception e) {
        return false;
    } finally {
        if (fileChannel != null) {
            try {
                fileChannel.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:com.bluexml.xforms.controller.alfresco.agents.MappingAgent.java

/**
 * Copies the content of a source file to a target file.
 * //from   w w w  .j a va 2s  . c  o m
 * @param sourceFile
 *            the source file
 * @param targetFile
 *            the target file
 * 
 * @throws ServletException
 *             the alfresco controller exception
 */
private void copyFile(File sourceFile, File targetFile) throws ServletException {
    FileChannel srcChannel = null;
    FileChannel dstChannel = null;
    try {
        try {
            srcChannel = new FileInputStream(sourceFile).getChannel();
            dstChannel = new FileOutputStream(targetFile).getChannel();
            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        } catch (IOException e) {
            throw new ServletException(e);
        } finally {
            if (srcChannel != null)
                srcChannel.close();
            if (dstChannel != null)
                dstChannel.close();
        }
    } catch (Exception e) {
        throw new ServletException(e);
    }
}

From source file:com.dotmarketing.util.ImportExportUtil.java

/**
 *
 * @param zipFile/*from  ww w . j av a 2s  .  c o  m*/
 * @return
 */
public boolean validateZipFile(File zipFile) {

    String tempdir = getBackupTempFilePath();
    try {
        deleteTempFiles();

        File ftempDir = new File(tempdir);
        ftempDir.mkdirs();
        File tempZip = new File(tempdir + File.separator + zipFile.getName());
        tempZip.createNewFile();
        FileChannel ic = new FileInputStream(zipFile).getChannel();
        FileChannel oc = new FileOutputStream(tempZip).getChannel();

        // to handle huge zipfiles
        ic.transferTo(0, ic.size(), oc);

        ic.close();
        oc.close();

        /*
         * Unzip zipped backups
         */
        if (zipFile != null && zipFile.getName().toLowerCase().endsWith(".zip")) {
            ZipFile z = new ZipFile(zipFile);
            ZipUtil.extract(z, new File(backupTempFilePath));
        }
        return true;

    } catch (Exception e) {
        Logger.error(this, "Error with file", e);
        return false;
    }
}

From source file:com.cerema.cloud2.operations.UploadFileOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    boolean localCopyPassed = false, nameCheckPassed = false;
    File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null;
    try {/*from   w w w.j  av a2 s  .c  o  m*/
        // / rename the file to upload, if necessary
        if (!mForceOverwrite) {
            String remotePath = getAvailableRemotePath(client, mRemotePath);
            mWasRenamed = !remotePath.equals(mRemotePath);
            if (mWasRenamed) {
                createNewOCFile(remotePath);
            }
        }
        nameCheckPassed = true;

        String expectedPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); // /
                                                                                            // not
                                                                                            // before
                                                                                            // getAvailableRemotePath()
                                                                                            // !!!
        expectedFile = new File(expectedPath);

        // check location of local file; if not the expected, copy to a
        // temporal file before upload (if COPY is the expected behaviour)
        if (!mOriginalStoragePath.equals(expectedPath)
                && mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_COPY) {

            if (FileStorageUtils.getUsableSpace(mAccount.name) < originalFile.length()) {
                result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_FULL);
                return result; // error condition when the file should be
                               // copied

            } else {

                String temporalPath = FileStorageUtils.getTemporalPath(mAccount.name) + mFile.getRemotePath();
                mFile.setStoragePath(temporalPath);
                temporalFile = new File(temporalPath);

                File temporalParent = temporalFile.getParentFile();
                temporalParent.mkdirs();
                if (!temporalParent.isDirectory()) {
                    throw new IOException("Unexpected error: parent directory could not be created");
                }
                temporalFile.createNewFile();
                if (!temporalFile.isFile()) {
                    throw new IOException("Unexpected error: target file could not be created");
                }

                InputStream in = null;
                OutputStream out = null;

                try {

                    // In case document provider schema as 'content://'
                    if (mOriginalStoragePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {

                        Uri uri = Uri.parse(mOriginalStoragePath);

                        in = MainApp.getAppContext().getContentResolver().openInputStream(uri);
                        out = new FileOutputStream(temporalFile);

                        int nRead;
                        byte[] data = new byte[16384];

                        while (!mCancellationRequested.get() && (nRead = in.read(data, 0, data.length)) != -1) {
                            out.write(data, 0, nRead);
                        }
                        out.flush();

                    } else {
                        if (!mOriginalStoragePath.equals(temporalPath)) { // preventing
                            // weird
                            // but
                            // possible
                            // situation

                            in = new FileInputStream(originalFile);
                            out = new FileOutputStream(temporalFile);
                            byte[] buf = new byte[1024];
                            int len;
                            while (!mCancellationRequested.get() && (len = in.read(buf)) > 0) {
                                out.write(buf, 0, len);
                            }
                        }
                    }

                    if (mCancellationRequested.get()) {
                        result = new RemoteOperationResult(new OperationCancelledException());
                    }

                } catch (Exception e) {
                    result = new RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_COPIED);
                    return result;

                } finally {
                    try {
                        if (in != null)
                            in.close();
                    } catch (Exception e) {
                        Log_OC.d(TAG, "Weird exception while closing input stream for " + mOriginalStoragePath
                                + " (ignoring)", e);
                    }
                    try {
                        if (out != null)
                            out.close();
                    } catch (Exception e) {
                        Log_OC.d(TAG, "Weird exception while closing output stream for " + expectedPath
                                + " (ignoring)", e);
                    }
                }
            }
        }
        localCopyPassed = (result == null);

        /// perform the upload
        if (mChunked
                && (new File(mFile.getStoragePath())).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE) {
            mUploadOperation = new ChunkedUploadRemoteFileOperation(mFile.getStoragePath(),
                    mFile.getRemotePath(), mFile.getMimetype(), mFile.getEtagInConflict());
        } else {
            mUploadOperation = new UploadRemoteFileOperation(mFile.getStoragePath(), mFile.getRemotePath(),
                    mFile.getMimetype(), mFile.getEtagInConflict());
        }
        Iterator<OnDatatransferProgressListener> listener = mDataTransferListeners.iterator();
        while (listener.hasNext()) {
            mUploadOperation.addDatatransferProgressListener(listener.next());
        }
        if (mCancellationRequested.get()) {
            throw new OperationCancelledException();
        }

        result = mUploadOperation.execute(client);

        /// move local temporal file or original file to its corresponding
        // location in the ownCloud local folder
        if (result.isSuccess()) {
            if (mLocalBehaviour == FileUploader.LOCAL_BEHAVIOUR_FORGET) {
                mFile.setStoragePath("");
            } else {
                mFile.setStoragePath(expectedPath);
                File fileToMove = null;
                if (temporalFile != null) { // FileUploader.LOCAL_BEHAVIOUR_COPY
                    // ; see where temporalFile was
                    // set
                    fileToMove = temporalFile;
                } else { // FileUploader.LOCAL_BEHAVIOUR_MOVE
                    fileToMove = originalFile;
                }
                if (!expectedFile.equals(fileToMove)) {
                    File expectedFolder = expectedFile.getParentFile();
                    expectedFolder.mkdirs();

                    if (expectedFolder.isDirectory()) {
                        if (!fileToMove.renameTo(expectedFile)) {
                            // try to copy and then delete
                            expectedFile.createNewFile();
                            FileChannel inChannel = new FileInputStream(fileToMove).getChannel();
                            FileChannel outChannel = new FileOutputStream(expectedFile).getChannel();

                            try {
                                inChannel.transferTo(0, inChannel.size(), outChannel);
                                fileToMove.delete();
                            } catch (Exception e) {
                                mFile.setStoragePath(null); // forget the local file
                                // by now, treat this as a success; the file was
                                // uploaded; the user won't like that the local file
                                // is not linked, but this should be a very rare
                                // fail;
                                // the best option could be show a warning message
                                // (but not a fail)
                                // result = new
                                // RemoteOperationResult(ResultCode.LOCAL_STORAGE_NOT_MOVED);
                                // return result;
                            } finally {
                                if (inChannel != null)
                                    inChannel.close();
                                if (outChannel != null)
                                    outChannel.close();
                            }
                        }

                    } else {
                        mFile.setStoragePath(null);
                    }
                }
            }
            FileDataStorageManager.triggerMediaScan(originalFile.getAbsolutePath());
            FileDataStorageManager.triggerMediaScan(expectedFile.getAbsolutePath());
        } else if (result.getHttpCode() == HttpStatus.SC_PRECONDITION_FAILED) {
            result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);

    } finally {
        if (temporalFile != null && !originalFile.equals(temporalFile)) {
            temporalFile.delete();
        }
        if (result == null) {
            result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR);
        }
        if (result.isSuccess()) {
            Log_OC.i(TAG,
                    "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": " + result.getLogMessage());
        } else {
            if (result.getException() != null) {
                String complement = "";
                if (!nameCheckPassed) {
                    complement = " (while checking file existence in server)";
                } else if (!localCopyPassed) {
                    complement = " (while copying local file to " + FileStorageUtils.getSavePath(mAccount.name)
                            + ")";
                }
                Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": "
                        + result.getLogMessage() + complement, result.getException());
            } else {
                Log_OC.e(TAG, "Upload of " + mOriginalStoragePath + " to " + mRemotePath + ": "
                        + result.getLogMessage());
            }
        }
    }

    return result;
}

From source file:org.opencastproject.util.FileSupport.java

/**
 * Copies the specified <code>sourceLocation</code> to <code>targetLocation</code> and returns a reference to the
 * newly created file or directory.//from ww w  .  ja va2s .  co  m
 * <p/>
 * If <code>targetLocation</code> is an existing directory, then the source file or directory will be copied into this
 * directory, otherwise the source file will be copied to the file identified by <code>targetLocation</code>.
 * <p/>
 * If <code>overwrite</code> is set to <code>false</code>, this method throws an {@link IOException} if the target
 * file already exists.
 * <p/>
 * Note that if <code>targetLocation</code> is a directory than the directory itself, not only its content is copied.
 * 
 * @param sourceFile
 *          the source file or directory
 * @param targetFile
 *          the directory to copy the source file or directory to
 * @param overwrite
 *          <code>true</code> to overwrite existing files
 * @return the created copy
 * @throws IOException
 *           if copying of the file or directory failed
 */
public static File copy(File sourceFile, File targetFile, boolean overwrite) throws IOException {

    // This variable is used when the channel copy files, and stores the maximum size of the file parts copied from source to target
    final int chunk = 1024 * 1024 * 512; // 512 MB

    // This variable is used when the cannel copy fails completely, as the size of the memory buffer used to copy the data from one stream to the other.
    final int bufferSize = 1024 * 1024; // 1 MB 

    File dest = determineDestination(targetFile, sourceFile, overwrite);

    // We are copying a directory
    if (sourceFile.isDirectory()) {
        if (!dest.exists()) {
            dest.mkdirs();
        }
        File[] children = sourceFile.listFiles();
        for (File child : children) {
            copy(child, dest, overwrite);
        }
    }
    // We are copying a file
    else {
        // If dest is not an "absolute file", getParentFile may return null, even if there *is* a parent file.
        // That's why "getAbsoluteFile" is used here
        dest.getAbsoluteFile().getParentFile().mkdirs();
        if (dest.exists())
            delete(dest);

        FileChannel sourceChannel = null;
        FileChannel targetChannel = null;
        FileInputStream sourceStream = null;
        FileOutputStream targetStream = null;
        long size = 0;

        try {
            sourceStream = new FileInputStream(sourceFile);
            targetStream = new FileOutputStream(dest);
            try {
                sourceChannel = sourceStream.getChannel();
                targetChannel = targetStream.getChannel();
                size = targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
            } catch (IOException ioe) {
                logger.warn("Got IOException using Channels for copying.");
            } finally {
                // This has to be in "finally", because in 64-bit machines the channel copy may fail to copy the whole file without causing a exception
                if ((sourceChannel != null) && (targetChannel != null) && (size < sourceFile.length()))
                    // Failing back to using FileChannels *but* with chunks and not altogether
                    logger.info("Trying to copy the file in chunks using Channels");
                if (size != sourceFile.length()) {
                    while (size < sourceFile.length())
                        size += targetChannel.transferFrom(sourceChannel, size, chunk);
                }
            }
        } catch (IOException ioe) {
            if ((sourceStream != null) && (targetStream != null) && (size < sourceFile.length())) {
                logger.warn(
                        "Got IOException using Channels for copying in chunks. Trying to use stream copy instead...");
                int copied = 0;
                byte[] buffer = new byte[bufferSize];
                while ((copied = sourceStream.read(buffer, 0, buffer.length)) != -1)
                    targetStream.write(buffer, 0, copied);
            } else
                throw ioe;
        } finally {
            if (sourceChannel != null)
                sourceChannel.close();
            if (sourceStream != null)
                sourceStream.close();
            if (targetChannel != null)
                targetChannel.close();
            if (targetStream != null)
                targetStream.close();
        }

        if (sourceFile.length() != dest.length()) {
            logger.warn("Source " + sourceFile + " and target " + dest + " do not have the same length");
            // TOOD: Why would this happen?
            // throw new IOException("Source " + sourceLocation + " and target " +
            // dest + " do not have the same length");
        }
    }
    return dest;
}

From source file:automenta.knowtention.channel.LineFileChannel.java

@Override
public void run() {

    FileInputStream fileInputStream = null;
    FileChannel channel = null;
    ByteBuffer buffer = null;/* w  w  w  .j av a  2  s.  c  o  m*/
    LinkedList<String> lines = new LinkedList();
    StringBuilder builder = new StringBuilder();
    long lastSize = -1, lastLastModified = -1;

    while (running) {
        try {
            Thread.sleep(delayPeriodMS);
        } catch (InterruptedException ex) {
        }

        lines.clear();
        try {
            fileInputStream = new FileInputStream(file);

            channel = fileInputStream.getChannel();

            long lastModified = file.lastModified();
            long csize = channel.size();
            if ((lastModified == lastLastModified) && (csize == lastSize)) { //also check file update time?
                fileInputStream.close();
                continue;
            }

            int currentPos = (int) csize;

            buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, csize);
            buffer.position(currentPos);
            lastSize = csize;
            lastLastModified = lastModified;

            int count = 0;

            for (long i = csize - 1; i >= 0; i--) {

                char c = (char) buffer.get((int) i);

                if (c == '\n') {
                    count++;
                    builder.reverse();
                    lines.addFirst(builder.toString());
                    if (count == numLines) {
                        break;
                    }
                    builder.setLength(0);
                } else
                    builder.append(c);
            }

            update(lines);

            lines.clear();
            buffer.clear();
            channel.close();
            fileInputStream.close();
            fileInputStream = null;

        } catch (Exception ex) {
            Logger.getLogger(LineFileChannel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    try {
        channel.close();
    } catch (IOException ex) {
        Logger.getLogger(LineFileChannel.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.owncloud.android.lib.resources.files.ChunkedUploadRemoteFileOperation.java

@Override
protected int uploadFile(OwnCloudClient client) throws HttpException, IOException {
    int status = -1;

    FileChannel channel = null;
    RandomAccessFile raf = null;/*from   w w  w .  ja  v a 2 s. c o m*/
    try {
        File file = new File(mLocalPath);
        raf = new RandomAccessFile(file, "r");
        channel = raf.getChannel();
        mEntity = new ChunkFromFileChannelRequestEntity(channel, mMimeType, CHUNK_SIZE, file);
        //((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(getDataTransferListeners());
        synchronized (mDataTransferListeners) {
            ((ProgressiveDataTransferer) mEntity).addDatatransferProgressListeners(mDataTransferListeners);
        }

        long offset = 0;
        String uriPrefix = client.getWebdavUri() + WebdavUtils.encodePath(mRemotePath) + "-chunking-"
                + Math.abs((new Random()).nextInt(9000) + 1000) + "-";
        long chunkCount = (long) Math.ceil((double) file.length() / CHUNK_SIZE);
        for (int chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++, offset += CHUNK_SIZE) {
            if (mPutMethod != null) {
                mPutMethod.releaseConnection(); // let the connection available for other methods
            }
            mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex);
            mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER);
            ((ChunkFromFileChannelRequestEntity) mEntity).setOffset(offset);
            mPutMethod.setRequestEntity(mEntity);
            status = client.executeMethod(mPutMethod);
            client.exhaustResponse(mPutMethod.getResponseBodyAsStream());
            Log_OC.d(TAG, "Upload of " + mLocalPath + " to " + mRemotePath + ", chunk index " + chunkIndex
                    + ", count " + chunkCount + ", HTTP result status " + status);
            if (!isSuccess(status))
                break;
        }

    } finally {
        if (channel != null)
            channel.close();
        if (raf != null)
            raf.close();
        if (mPutMethod != null)
            mPutMethod.releaseConnection(); // let the connection available for other methods
    }
    return status;
}

From source file:org.apache.nifi.processors.standard.TailFile.java

private FileChannel createReader(final File file, final long position) {
    final FileChannel reader;

    try {/*  www .  j a  v  a  2 s  . c  o  m*/
        reader = FileChannel.open(file.toPath(), StandardOpenOption.READ);
    } catch (final IOException ioe) {
        getLogger().warn(
                "Unable to open file {}; will attempt to access file again after the configured Yield Duration has elapsed: {}",
                new Object[] { file, ioe });
        return null;
    }

    getLogger().debug("Created FileChannel {} for {}", new Object[] { reader, file });

    try {
        reader.position(position);
    } catch (final IOException ioe) {
        getLogger().error("Failed to read from {} due to {}", new Object[] { file, ioe });

        try {
            reader.close();
            getLogger().debug("Closed FileChannel {}", new Object[] { reader });
        } catch (final IOException ioe2) {
        }

        return null;
    }

    return reader;
}

From source file:org.wso2.developerstudio.eclipse.registry.apim.views.RegistryBrowserAPIMView.java

private void copyFileToFile(File source, File dest) throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {/* w w w .j  a  va2s.  c o m*/
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.importer.ArchiveImporterJob.java

private boolean copyFile(File in, File out) {
    boolean bRet = false;

    FileChannel inChannel = null;
    FileChannel outChannel = null;

    try {//from w w  w  .ja  v a2 s  .com
        inChannel = new FileInputStream(in).getChannel();
        outChannel = new FileOutputStream(out).getChannel();

        // On the Windows plateform, you can't copy a file bigger than 64Mb, an
        // Exception in thread "main" java.io.IOException: Insufficient system
        // resources exist to complete the requested service is thrown.
        // inChannel.transferTo(0, inChannel.size(), outChannel);

        // magic number for Windows, 64Mb - 32Kb)
        int maxCount = (64 * 1024 * 1024) - (32 * 1024);
        long size = inChannel.size();
        long position = 0;
        while (position < size) {
            position += inChannel.transferTo(position, maxCount, outChannel);
        }

        bRet = true;

    } catch (IOException e) {
        //System.out.println( e );
        //throw e;
    } finally {
        try {
            if (inChannel != null)
                inChannel.close();
        } catch (IOException e) {
        }
        try {
            if (outChannel != null)
                outChannel.close();
        } catch (IOException e) {
        }
    }
    return bRet;
}