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:com.buaa.cfs.nfs3.WriteCtx.java

/**
 * Writing the data into a local file. After the writing, if {@link #dataState} is still ALLOW_DUMP, set {@link
 * #data} to null and set {@link #dataState} to DUMPED.
 *///from w w  w .  j ava  2 s  .c  o m
long dumpData(FileOutputStream dumpOut, RandomAccessFile raf) throws IOException {
    if (dataState != DataState.ALLOW_DUMP) {
        if (LOG.isTraceEnabled()) {
            LOG.trace(
                    "No need to dump with status(replied,dataState):" + "(" + replied + "," + dataState + ")");
        }
        return 0;
    }

    // Resized write should not allow dump
    Preconditions.checkState(originalCount == INVALID_ORIGINAL_COUNT);

    this.raf = raf;
    dumpFileOffset = dumpOut.getChannel().position();
    dumpOut.write(data.array(), 0, count);
    if (LOG.isDebugEnabled()) {
        LOG.debug("After dump, new dumpFileOffset:" + dumpFileOffset);
    }
    // it is possible that while we dump the data, the data is also being
    // written back to HDFS. After dump, if the writing back has not finished
    // yet, we change its flag to DUMPED and set the data to null. Otherwise
    // this WriteCtx instance should have been removed from the buffer.
    if (dataState == DataState.ALLOW_DUMP) {
        synchronized (this) {
            if (dataState == DataState.ALLOW_DUMP) {
                data = null;
                dataState = DataState.DUMPED;
                return count;
            }
        }
    }
    return 0;
}

From source file:org.geoserver.platform.resource.FileLockProvider.java

public Resource.Lock acquire(final String lockKey) {
    // first off, synchronize among threads in the same jvm (the nio locks won't lock 
    // threads in the same JVM)
    final Resource.Lock memoryLock = memoryProvider.acquire(lockKey);

    // then synch up between different processes
    final File file = getFile(lockKey);
    try {//  ww w  .j  av  a2 s.c  o m
        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 IllegalStateException(
                        "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;

            return new Resource.Lock() {

                boolean released;

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

                    try {
                        released = true;
                        if (!lock.isValid()) {
                            // do not crap out, locks usage 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 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);
                            file.delete();

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

                @Override
                public String toString() {
                    return "FileLock " + file.getName();
                }
            };
        } finally {
            if (currLock != null) {
                currLock.release();
                memoryLock.release();
            }
            IOUtils.closeQuietly(currFos);
            file.delete();
        }
    } catch (IOException e) {
        throw new IllegalStateException("Failure while trying to get lock for key " + lockKey, e);
    }
}

From source file:com.mgmtp.perfload.perfalyzer.binning.Binner.java

/**
 * Performs the binning operation on the specified file.
 *
 * @param file//from w  w  w  .  j a v  a 2s.c o m
 *       the file to be binned and/or aggregated; must be relative to the source directory
 */
public void binFile(final PerfAlyzerFile file) throws IOException {
    FileOutputStream fos = null;
    try (FileInputStream fis = new FileInputStream(new File(sourceDir, file.getFile().getPath()));
            ChannelManager channelManager = new ChannelManager(destDir,
                    channelKey -> file.copy().addFileNamePart(channelKey))) {

        Scanner scanner = new Scanner(fis.getChannel(), Charsets.UTF_8.name());
        if (binningStrategy.needsBinning()) {
            File destFile = new File(destDir, binningStrategy.transformDefautBinnedFilePath(file));
            Files.createParentDirs(destFile);
            fos = new FileOutputStream(destFile);
            binningStrategy.binData(scanner, fos.getChannel());
        } else {
            // if binning is not necessary, no channel is provided
            binningStrategy.binData(scanner, null);
        }

        binningStrategy.aggregateData(channelManager);
    } finally {
        closeQuietly(fos);
    }
}

From source file:com.att.api.oauth.OAuthToken.java

/**
 * Saves this token to a file in an asynchronous-safe manner.
 *
 * @param fpath file path//from   w  w w. j  a v  a 2  s.c  o m
 * @throws IOException if unable to save token
 */
public void saveToken(String fpath) throws IOException {
    FileOutputStream fOutputStream = null;
    FileLock fLock = null;

    // save to cached tokens
    synchronized (LOCK_OBJECT) {
        // lazy init
        if (cachedTokens == null) {
            cachedTokens = new HashMap<String, OAuthToken>();
        }
        OAuthToken.cachedTokens.put(fpath, this);

        try {
            fOutputStream = new FileOutputStream(fpath);
            fLock = fOutputStream.getChannel().lock();
            Properties props = new Properties();
            props.setProperty("accessToken", accessToken);
            props.setProperty("creationTime", String.valueOf(creationTime));
            props.setProperty("expiresIn", String.valueOf(expiresIn));
            props.setProperty("refreshToken", refreshToken);
            props.store(fOutputStream, "Token Information");
        } catch (IOException e) {
            throw e; // pass along exception
        } finally {
            if (fLock != null) {
                fLock.release();
            }
            if (fOutputStream != null) {
                fOutputStream.close();
            }
        }
    }
}

From source file:Interface.FramePrincipal.java

private void bt_atuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_atuActionPerformed

    ///////////////////////////////////////////// Baixa xml do bucket //////////////////////////////////////////////////////////        
    File diretorio = new File(dir_dow.getText());

    if ("".equals(dir_dow.getText())) {
        JOptionPane.showMessageDialog(null, "Campo diretrio deve ser preenchido!");
    } else if (!diretorio.exists()) {
        JOptionPane.showMessageDialog(null, "Este no  um diretrio vlido!");
    } else {/*from w w  w.  j  a  v a  2s  .  co m*/
        try {
            URL arquivoBucket = new URL("http://storage.googleapis.com/" + bac.getNome());

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

            //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);

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

            /////////////////////////////// Carrega tabela com nome de arquivos ////////////////////////////////////////////////////       
            //percorret tabela
            DefaultTableModel adm = (DefaultTableModel) jTable.getModel();
            adm.setNumRows(0);
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            //Importar arquivo xml         
            File file = new File(dir_dow.getText() + "/" + bac.getNome() + ".xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(file);
            doc.getDocumentElement().normalize();
            System.out.println("Root element " + doc.getDocumentElement().getNodeName());
            NodeList nodeLst = doc.getElementsByTagName("Contents");
            System.out.println("Information of all employees");

            for (int s = 0; s < nodeLst.getLength(); s++) {

                Node fstNode = nodeLst.item(s);

                if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element fstElmnt = (Element) fstNode;
                    NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("Key");
                    Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                    NodeList fstNm = fstNmElmnt.getChildNodes();
                    System.out.println("Key : " + ((Node) fstNm.item(0)).getNodeValue());

                    String val = ((Node) fstNm.item(0)).getNodeValue();

                    adm.addRow(new Object[] { val });

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static boolean copyFile(File sourceFile, File destFile) throws IOException {
    if (!destFile.exists()) {
        destFile.createNewFile();/*  www.j  a v  a  2  s. co  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(e);
        return false;
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
    return true;
}

From source file:com.skcraft.launcher.launch.JavaRuntimeFetcher.java

private void copyFile(InputStream source, File destination, String status, long length) {
    ReadableByteChannel byteChannel = null;
    FileOutputStream outputStream = null;
    try {//from w ww.j  a va 2 s .c o m
        if (destination.getParentFile().mkdirs()) {
            log.log(Level.INFO, "Creating dir: {0}", destination.getParentFile());
        }

        if (destination.createNewFile()) {
            log.log(Level.INFO, "Creating file: {0}", destination);
        }

        byteChannel = Channels.newChannel(source);
        outputStream = new FileOutputStream(destination);

        if (length < 0) {
            getProgress().set(status, -1);
            outputStream.getChannel().transferFrom(byteChannel, 0, Long.MAX_VALUE);
        } else {
            long position = 0;
            long increment = length / 100L;
            while (position < length) {
                outputStream.getChannel().transferFrom(byteChannel, position, increment);
                position += increment;

                double progress = (double) position / (double) length;
                getProgress().set(status, progress);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        Closer.close(byteChannel);
        Closer.close(outputStream);
    }
}

From source file:org.geowebcache.storage.blobstore.file.FileBlobStore.java

private void writeFile(File target, TileObject stObj, boolean existed) throws StorageException {
    // first write to temp file
    tmp.mkdirs();//w ww  .j a  va2 s. c  om
    File temp = new File(tmp, UUID.randomUUID().toString());

    try {
        // Open the output stream and read the blob into the tile
        FileOutputStream fos = null;
        FileChannel channel = null;
        try {
            fos = new FileOutputStream(temp);

            channel = fos.getChannel();
            try {
                stObj.getBlob().transferTo(channel);
            } catch (IOException ioe) {
                throw new StorageException(ioe.getMessage() + " for " + target.getAbsolutePath());
            } finally {
                try {
                    if (channel != null) {
                        channel.close();
                    }
                } catch (IOException ioe) {
                    throw new StorageException(ioe.getMessage() + " for " + target.getAbsolutePath());
                }
            }
        } catch (FileNotFoundException ioe) {
            throw new StorageException(ioe.getMessage() + " for " + target.getAbsolutePath());
        } finally {
            IOUtils.closeQuietly(fos);
        }

        // rename to final position. This will fail if another GWC also wrote this
        // file, in such case we'll just eliminate this one
        if (FileUtils.renameFile(temp, target)) {
            temp = null;
        } else if (existed) {
            // if we are trying to overwrite and old tile, on windows that might fail... delete
            // and rename instead
            if (target.delete() && FileUtils.renameFile(temp, target)) {
                temp = null;
            }
        }
    } finally {

        if (temp != null) {
            log.warn("Tile " + target.getPath() + " was already written by another thread/process");
            temp.delete();
        }
    }

}

From source file:tvhchgen.Service.java

/**
 * Save the content of the Url to the given path
 * @param urlStr/*from  ww w  . j a v a2  s . co  m*/
 * @param outPath
 * @return 
 */
public boolean saveUrl(String urlStr, String outPath) {
    InputStream is = null;
    try {
        //System.out.println( "Getting: " + urlStr );
        URL url = new URL(urlStr);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpURLConnection.setFollowRedirects(true);
        // allow both GZip and Deflate (ZLib) encodings
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT);
        conn.setRequestProperty("Referer", DEFAULT_REFERER);
        String encoding = conn.getContentEncoding();
        InputStream inStr;

        // create the appropriate stream wrapper based on
        // the encoding type
        if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
            inStr = new GZIPInputStream(conn.getInputStream());
        } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
            inStr = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
        } else {
            inStr = conn.getInputStream();
        }

        //System.out.println( filePath );
        File file = new File(outPath);
        if (!file.exists()) {
            file.createNewFile();

            FileOutputStream fos = new FileOutputStream(file);
            ReadableByteChannel rbc = Channels.newChannel(inStr);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
            return true;
        }
    } catch (Exception e) {
        System.out.println("Exception: " + e.toString());
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
                System.out.println("Exception: " + e.toString());
            }
        }
    }
    return false;
}