Example usage for java.io FileOutputStream getChannel

List of usage examples for java.io FileOutputStream getChannel

Introduction

In this page you can find the example usage for java.io FileOutputStream getChannel.

Prototype

public FileChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.FileChannel FileChannel object associated with this file output stream.

Usage

From source file:pl.psnc.synat.wrdz.zmd.download.adapters.HttpDownloadAdapter.java

@Override
public String downloadFile(URI uri, String relativePath) throws DownloadAdapterException {
    String cachedFilePath = getResourceCachePath(relativePath);
    checkDestinationExistence(cachedFilePath);
    DefaultHttpClient httpclient = new DefaultHttpClient();
    ReadableByteChannel rbc = null;
    FileOutputStream output = null;
    try {/*from ww w. ja va 2 s  .c o  m*/
        if (usernamePasswordCredentials != null) {
            httpclient.getCredentialsProvider().setCredentials(authScope, usernamePasswordCredentials);
        }
        HttpResponse response = httpclient.execute(new HttpGet(uri));
        HttpEntity entity = response.getEntity();
        if (entity != null && response.getStatusLine().getStatusCode() == 200) {
            rbc = Channels.newChannel(entity.getContent());
            output = new FileOutputStream(cachedFilePath);
            output.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            EntityUtils.consume(entity);
        } else {
            EntityUtils.consume(entity);
            throw new DownloadAdapterException(
                    "Http error code or empty content was returned instead of resource.");
        }

    } catch (IOException e) {
        throw new DownloadAdapterException("Exception caught while downloading file contents to the cache.", e);
    } finally {
        httpclient.getConnectionManager().shutdown();
        try {
            if (rbc != null) {
                rbc.close();
            }
            if (output != null) {
                output.close();
            }
        } catch (IOException e) {
            throw new DownloadAdapterException("Exception caught while closing input/output streams.", e);
        }
    }
    return cachedFilePath;
}

From source file:Interface.FramePrincipal.java

private void bt_dowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_dowActionPerformed
    File dir = new File(dir_dow.getText());

    if ("".equals(dir_dow.getText())) {
        JOptionPane.showMessageDialog(null, "Campo diretrio no pode estar vazio!");
    } else if (!dir.exists()) {
        JOptionPane.showMessageDialog(null, "Informe um diretrio vlido!");
    } else {/* w w w . j a va2 s.  c om*/
        try {

            URL arquivoBucket = new URL("https://console.developers.google.com/m/cloudstorage/b/"
                    + bac.getNome() + "/o/" + arquivo);

            //Passa caminho de saida do arquivo que esta sendo baixado
            ReadableByteChannel canalArquivoSaida = Channels.newChannel(arquivoBucket.openStream());
            FileOutputStream arquivoSaida = new FileOutputStream(dir_dow.getText() + "/" + arquivo);

            //Calcula tempo que o processo de download levou
            long inicio = System.currentTimeMillis();
            arquivoSaida.getChannel().transferFrom(canalArquivoSaida, 0, 1 << 24);
            long fim = System.currentTimeMillis();
            System.out.println(fim - inicio);

            JOptionPane.showMessageDialog(null, "Arquivo baixado com sucesso!");

            arquivoSaida.close(); //libera o arquivo aps ser baixado.

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Arquivo no possui permisso para download!");

        }
    }
}

From source file:org.multibit.file.FileHandler.java

public static void copyFile(File sourceFile, File destinationFile) throws IOException {
    if (!destinationFile.exists()) {
        destinationFile.createNewFile();
    }//  w ww. j  a  va  2 s  . c  o m
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    FileChannel source = null;
    FileChannel destination = null;
    try {
        fileInputStream = new FileInputStream(sourceFile);
        source = fileInputStream.getChannel();
        fileOutputStream = new FileOutputStream(destinationFile);
        destination = fileOutputStream.getChannel();
        long transfered = 0;
        long bytes = source.size();
        while (transfered < bytes) {
            transfered += destination.transferFrom(source, 0, source.size());
            destination.position(transfered);
        }
    } finally {
        if (source != null) {
            source.close();
            source = null;
        } else if (fileInputStream != null) {
            fileInputStream.close();
            fileInputStream = null;
        }
        if (destination != null) {
            destination.close();
            destination = null;
        } else if (fileOutputStream != null) {
            fileOutputStream.flush();
            fileOutputStream.close();
        }
    }
}

From source file:org.orbisgis.orbisserver.baseserver.model.Session.java

/**
 * Generate an archive with the result of the job available on the server.
 * @param jobId Id of the job which has generated the results.
 * @return File object of the archive containing the results. If an error appends in the archive creation, returns null.
 *///ww w.  j a v a 2  s .c om
public File getResultAchive(String jobId) {
    File jobFolder = new File(workspaceFolder, jobId);
    for (StatusInfo statusInfo : getAllStatusInfo()) {
        if (statusInfo.getJobId().equalsIgnoreCase(jobId)) {
            //Once the good StatusInfo in found, for each output store its data in the archive
            for (Output out : statusInfo.getResult().getOutputList()) {
                //In the case of plain data, write it into a file
                if (out.getData() != null) {
                    try {
                        for (Object content : out.getData().getContent()) {
                            File outFile;
                            //If a file with the output name already exists, adds a number to it
                            if (jobFolder.list(new NameFileFilter(out.getTitle())) != null) {
                                int diff = 1;
                                while (jobFolder.list(new NameFileFilter(out.getTitle() + diff)) != null) {
                                    diff++;
                                }
                                outFile = new File(jobFolder,
                                        out.getTitle().replaceAll(File.separator, "") + diff);
                            } else {
                                outFile = new File(jobFolder, out.getTitle().replaceAll(File.separator, ""));
                            }
                            //Create the file and write data inside
                            if (jobFolder.mkdirs() || outFile.createNewFile()) {
                                try (FileWriter fileWriter = new FileWriter(outFile)) {
                                    try (PrintWriter out1 = new PrintWriter(fileWriter)) {
                                        out1.append(content.toString());
                                    }
                                }
                            } else {
                                LOGGER.error("Unable to create the output as a file.");
                            }
                        }
                    } catch (IOException e) {
                        LOGGER.error("Unable to write the output as a file.\n" + e.getMessage());
                    }
                }
                //If the result is a reference, copy if to the archive folder
                else if (out.getReference() != null) {
                    try {
                        URL url = new URL(out.getReference());
                        ReadableByteChannel readableByteChannel = Channels.newChannel(url.openStream());
                        FileOutputStream fos = new FileOutputStream(out.getTitle());
                        fos.getChannel().transferFrom(readableByteChannel, 0, Long.MAX_VALUE);
                    } catch (IOException e) {
                        LOGGER.error("Unable to download the result.\n" + e.getMessage());
                    }
                }
            }
        }
    }
    try {
        //Create a zip file with the archive folder
        File zipFile = new File(workspaceFolder, "Result.zip");
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        for (File f : jobFolder.listFiles()) {
            FileInputStream fis = new FileInputStream(f);
            ZipEntry zipEntry = new ZipEntry(f.getName());
            zos.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zos.write(bytes, 0, length);
            }

            zos.closeEntry();
            fis.close();
        }
        zos.close();
        fos.close();
        return zipFile;
    } catch (IOException e) {
        LOGGER.error("Unable to zip the result folder.\n" + e.getMessage());
    }
    return null;
}

From source file:kr.wdream.storyshop.AndroidUtilities.java

public static boolean copyFile(File sourceFile, File destFile) throws IOException {
    if (!destFile.exists()) {
        destFile.createNewFile();/*from  w ww  . ja  va 2 s . c  o  m*/
    }
    FileInputStream source = null;
    FileOutputStream destination = null;
    try {
        source = new FileInputStream(sourceFile);
        destination = new FileOutputStream(destFile);
        destination.getChannel().transferFrom(source.getChannel(), 0, source.getChannel().size());
    } catch (Exception e) {
        FileLog.e("tmessages", e);
        return false;
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
    return true;
}

From source file:me.neatmonster.spacertk.actions.FileActions.java

/**
 * Sends a file to a URL/*from  w w  w .  j av  a  2s.  c o  m*/
 * @param url URL to send to
 * @param file File to send
 * @return If successful
 */
@Action(aliases = { "sendFile", "fileSend" })
public boolean sendFile(final String url, final String file) {
    FileOutputStream fileOutputStream = null;
    ReadableByteChannel readableByteChannel = null;
    try {
        File file_ = new File(file);
        if (file_.exists())
            if (!deleteFile(file_.getPath()))
                return false;
        URL url_ = new URL(url);
        readableByteChannel = Channels.newChannel(url_.openStream());
        fileOutputStream = new FileOutputStream(file_);
        fileOutputStream.getChannel().transferFrom(readableByteChannel, 0, 1 << 24);
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileOutputStream != null)
                fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (readableByteChannel != null)
                readableByteChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:org.opennms.features.newts.converter.rrd.converter.JRobinConverter.java

public boolean moveFileSafely(final File in, final File out) throws IOException {
    FileInputStream fis = null;/*  ww  w  .  ja v  a2 s.  co m*/
    FileOutputStream fos = null;
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    final File tempOut = File.createTempFile("move", ".tmp");
    try {
        fis = new FileInputStream(in);
        fos = new FileOutputStream(tempOut);
        inChannel = fis.getChannel();
        outChannel = fos.getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        try {
            if (inChannel != null)
                inChannel.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel);
        }
        try {
            if (outChannel != null)
                outChannel.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel);
        }
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis);
        }
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos);
        }
    }
    out.delete();
    if (!out.exists()) {
        tempOut.renameTo(out);
        return in.delete();
    }
    return false;
}

From source file:it.polimi.diceH2020.plugin.control.DICEWrap.java

/**
 * Builds PNML model file from ModelResult.
 * //from  ww  w .j a  va  2s. c  o  m
 * @param classID
 * @param alt
 */
public void generatePNML(String classID, String alt) {
    PetriNetDoc pnd = (PetriNetDoc) result.getModel().get(0);
    File aFile = new File(
            Preferences.getSavingDir() + conf.getID() + "J" + classID + alt.replaceAll("-", "") + ".pnml");
    FileOutputStream outputFile = null;
    try {
        outputFile = new FileOutputStream(aFile, true);
        System.out.println("File stream created successfully.");
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    FileChannel outChannel = outputFile.getChannel();
    pnd.toPNML(outChannel);
}

From source file:it.readbeyond.minstrel.commander.Commander.java

private void copyFile(String sourcePath, String destinationPath, final CallbackContext callbackContext) {
    String source = this.normalizePath(sourcePath);
    String destination = this.normalizePath(destinationPath);
    try {/* ww  w  .java  2 s .com*/
        File f = new File(source);
        if (f.exists()) {
            File d = new File(destination);

            // create parent directory, if not existing
            File destinationParent = d.getParentFile();
            destinationParent.mkdirs();

            // TODO check for write permission?
            // copy file
            FileInputStream inStream = new FileInputStream(f);
            FileOutputStream outStream = new FileOutputStream(d);
            FileChannel inChannel = inStream.getChannel();
            FileChannel outChannel = outStream.getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            inStream.close();
            outStream.close();
            callbackContext.success(MESSAGE_FILE_COPIED);

        } else {
            callbackContext.success(MESSAGE_FILE_DOES_NOT_EXIST);
        }
    } catch (Exception e) {
        callbackContext.success(MESSAGE_ERROR_WHILE_COPYING);
    }
}

From source file:org.geowebcache.locks.NIOLockProvider.java

public LockProvider.Lock getLock(final String lockKey) throws GeoWebCacheException {
    File file = null;/*from  w w w.ja v a 2s .  c  o m*/
    // first off, synchronize among threads in the same jvm (the nio locks won't lock 
    // threads in the same JVM)
    final LockProvider.Lock memoryLock = memoryProvider.getLock(lockKey);
    // then synch up between different processes
    try {
        file = getFile(lockKey);
        FileOutputStream currFos = null;
        FileLock currLock = null;
        try {
            // try to lock
            int count = 0;
            while (currLock == null && count < maxLockAttempts) {
                // the file output stream can also fail to be acquired due to the
                // other nodes deleting the file
                currFos = new FileOutputStream(file);
                try {
                    currLock = currFos.getChannel().lock();
                } catch (OverlappingFileLockException e) {
                    IOUtils.closeQuietly(currFos);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ie) {
                        // ok, moving on
                    }
                } catch (IOException e) {
                    // this one is also thrown with a message "avoided fs deadlock"
                    IOUtils.closeQuietly(currFos);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ie) {
                        // ok, moving on
                    }
                }
                count++;
            }

            // verify we managed to get the FS lock
            if (count >= maxLockAttempts) {
                throw new GeoWebCacheException(
                        "Failed to get a lock on key " + lockKey + " after " + count + " attempts");
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Lock " + lockKey + " acquired by thread " + Thread.currentThread().getId()
                        + " on file " + file);
            }

            // store the results in a final variable for the inner class to use
            final FileOutputStream fos = currFos;
            final FileLock lock = currLock;

            // nullify so that we don't close them, the locking occurred as expected
            currFos = null;
            currLock = null;

            final File lockFile = file;
            return new LockProvider.Lock() {

                boolean released;

                public void release() throws GeoWebCacheException {
                    if (released) {
                        return;
                    }

                    try {
                        released = true;
                        if (!lock.isValid()) {
                            // do not crap out, locks usage in GWC is only there to prevent duplication of work
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Lock key " + lockKey + " for releasing lock is unkonwn, it means "
                                        + "this lock was never acquired, or was released twice. "
                                        + "Current thread is: " + Thread.currentThread().getId() + ". "
                                        + "Are you running two GWC instances in the same JVM using NIO locks? "
                                        + "This case is not supported and will generate exactly this error message");
                                return;
                            }
                        }
                        try {
                            lock.release();
                            IOUtils.closeQuietly(fos);
                            lockFile.delete();

                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Lock " + lockKey + " released by thread "
                                        + Thread.currentThread().getId());
                            }
                        } catch (IOException e) {
                            throw new GeoWebCacheException(
                                    "Failure while trying to release lock for key " + lockKey, e);
                        }
                    } finally {
                        memoryLock.release();
                    }

                }
            };
        } finally {
            try {
                if (currLock != null) {
                    currLock.release();
                }
                IOUtils.closeQuietly(currFos);
                file.delete();
            } finally {
                memoryLock.release();
            }
        }
    } catch (IOException e) {
        throw new GeoWebCacheException("Failure while trying to get lock for key " + lockKey, e);
    }

}