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:org.apache.flex.utilities.converter.retrievers.download.DownloadRetriever.java

protected void performFastDownload(URL sourceUrl, File targetFile) throws IOException {
    final URLConnection connection = sourceUrl.openConnection();
    final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
    final FileOutputStream fos = new FileOutputStream(targetFile);

    ////////////////////////////////////////////////////////////////////////////////
    // Do the downloading.
    ////////////////////////////////////////////////////////////////////////////////

    final long expectedSize = connection.getContentLength();
    long transferedSize = 0L;

    System.out.println("===========================================================");
    System.out.println("Downloading " + sourceUrl.toString());
    if (expectedSize > 1014 * 1024) {
        System.out.println("Expected size: " + (expectedSize / 1024 / 1024) + "MB");
    } else {// ww w . ja  v  a 2  s .com
        System.out.println("Expected size: " + (expectedSize / 1024) + "KB");
    }
    final ProgressBar progressBar = new ProgressBar(expectedSize);
    while (transferedSize < expectedSize) {
        transferedSize += fos.getChannel().transferFrom(rbc, transferedSize, 1 << 20);
        progressBar.updateProgress(transferedSize);
    }
    fos.close();
    System.out.println();
    System.out.println("Finished downloading.");
    System.out.println("===========================================================");
}

From source file:org.opennms.install.Installer.java

/**
 * <p>copyFile</p>/*from  ww  w.  j a  va 2 s. c  o  m*/
 *
 * @param source a {@link java.lang.String} object.
 * @param destination a {@link java.lang.String} object.
 * @param description a {@link java.lang.String} object.
 * @param recursive a boolean.
 * @throws java.lang.Exception if any.
 */
public void copyFile(String source, String destination, String description, boolean recursive)
        throws Exception {
    File sourceFile = new File(source);
    File destinationFile = new File(destination);

    if (!sourceFile.exists()) {
        throw new Exception("source file (" + source + ") does not exist!");
    }
    if (!sourceFile.isFile()) {
        throw new Exception("source file (" + source + ") is not a file!");
    }
    if (!sourceFile.canRead()) {
        throw new Exception("source file (" + source + ") is not readable!");
    }
    if (destinationFile.exists()) {
        System.out.print("  - " + destination + " exists, removing... ");
        if (destinationFile.delete()) {
            System.out.println("REMOVED");
        } else {
            System.out.println("FAILED");
            throw new Exception("unable to delete existing file: " + sourceFile);
        }
    }

    System.out.print("  - copying " + source + " to " + destination + "... ");
    if (!destinationFile.getParentFile().exists()) {
        if (!destinationFile.getParentFile().mkdirs()) {
            throw new Exception("unable to create directory: " + destinationFile.getParent());
        }
    }
    if (!destinationFile.createNewFile()) {
        throw new Exception("unable to create file: " + destinationFile);
    }
    FileChannel from = null;
    FileInputStream fisFrom = null;
    FileChannel to = null;
    FileOutputStream fisTo = null;
    try {
        fisFrom = new FileInputStream(sourceFile);
        from = fisFrom.getChannel();
        fisTo = new FileOutputStream(destinationFile);
        to = fisTo.getChannel();
        to.transferFrom(from, 0, from.size());
    } catch (FileNotFoundException e) {
        throw new Exception("unable to copy " + sourceFile + " to " + destinationFile, e);
    } finally {
        IOUtils.closeQuietly(fisTo);
        IOUtils.closeQuietly(to);
        IOUtils.closeQuietly(fisFrom);
        IOUtils.closeQuietly(from);
    }
    System.out.println("DONE");
}

From source file:org.wso2.esb.integration.common.utils.ESBTestCaseUtils.java

/**
 * Copy the given source file to the given destination
 *
 * @param sourceUri source file location
 * @param destUri   destination file location
 * @throws IOException/*w w w  .  j  a  va  2s  .  co  m*/
 */
public static void copyFile(String sourceUri, String destUri) throws IOException {
    File sourceFile = new File(sourceUri);
    File destFile = new File(destUri);

    if (destFile.exists()) {
        destFile.delete();
    }
    destFile.createNewFile();
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;

    try {
        fileInputStream = new FileInputStream(sourceFile);
        fileOutputStream = new FileOutputStream(destFile);

        FileChannel source = fileInputStream.getChannel();
        FileChannel destination = fileOutputStream.getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:org.spoutcraft.launcher.api.util.Download.java

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;
    try {//from   w  ww  .j  a v  a2s  . com
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        ((HttpURLConnection) conn).setInstanceFollowRedirects(true);
        int response = ((HttpURLConnection) conn).getResponseCode();
        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (PermissionDeniedException e) {
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        result = Result.FAILURE;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

From source file:org.spoutcraft.launcher.util.Download.java

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;
    try {/*from  w  w  w  .  j a  v  a  2s .  co m*/
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        ((HttpURLConnection) conn).setInstanceFollowRedirects(true);
        int response = ((HttpURLConnection) conn).getResponseCode();
        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (PermissionDeniedException e) {
        exception = e;
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        exception = e;
        result = Result.FAILURE;
    } catch (Exception e) {
        exception = e;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

From source file:org.carbondata.core.util.CarbonUtil.java

public static void writeLevelCardinalityFile(String loadFolderLoc, String tableName, int[] dimCardinality)
        throws KettleException {
    String levelCardinalityFilePath = loadFolderLoc + File.separator + CarbonCommonConstants.LEVEL_METADATA_FILE
            + tableName + CarbonCommonConstants.CARBON_METADATA_EXTENSION;
    FileOutputStream fileOutputStream = null;
    FileChannel channel = null;/* w w  w  .  ja  va2  s  .c om*/
    try {
        int dimCardinalityArrLength = dimCardinality.length;

        // first four bytes for writing the length of array, remaining for array data
        ByteBuffer buffer = ByteBuffer.allocate(CarbonCommonConstants.INT_SIZE_IN_BYTE
                + dimCardinalityArrLength * CarbonCommonConstants.INT_SIZE_IN_BYTE);

        fileOutputStream = new FileOutputStream(levelCardinalityFilePath);
        channel = fileOutputStream.getChannel();
        buffer.putInt(dimCardinalityArrLength);

        for (int i = 0; i < dimCardinalityArrLength; i++) {
            buffer.putInt(dimCardinality[i]);
        }

        buffer.flip();
        channel.write(buffer);
        buffer.clear();

        LOGGER.info("Level cardinality file written to : " + levelCardinalityFilePath);
    } catch (IOException e) {
        LOGGER.error(
                "Error while writing level cardinality file : " + levelCardinalityFilePath + e.getMessage());
        throw new KettleException("Not able to write level cardinality file", e);
    } finally {
        closeStreams(channel, fileOutputStream);
    }
}

From source file:com.eucalyptus.blockstorage.DASManager.java

public void dupFile(String oldFileName, String newFileName) {
    FileOutputStream fileOutputStream = null;
    FileChannel out = null;/*w  w  w.  j  a  v a 2 s .  c om*/
    FileInputStream fileInputStream = null;
    FileChannel in = null;
    try {
        fileOutputStream = new FileOutputStream(new File(newFileName));
        out = fileOutputStream.getChannel();
        fileInputStream = new FileInputStream(new File(oldFileName));
        in = fileInputStream.getChannel();
        in.transferTo(0, in.size(), out);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (fileOutputStream != null) {
            try {
                out.close();
                fileOutputStream.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
        if (fileInputStream != null) {
            try {
                in.close();
                fileInputStream.close();
            } catch (IOException e) {
                LOG.error(e);
            }
        }
    }
}

From source file:org.apache.flex.utilities.converter.retrievers.download.DownloadRetriever.java

protected void performSafeDownload(URI sourceUri, File targetFile) throws IOException {
    HttpGet httpget = new HttpGet(sourceUri);
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(httpget);

    String reasonPhrase = response.getStatusLine().getReasonPhrase();
    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println(String.format("statusCode: %d", statusCode));
    System.out.println(String.format("reasonPhrase: %s", reasonPhrase));

    HttpEntity entity = response.getEntity();
    InputStream content = entity.getContent();

    final ReadableByteChannel rbc = Channels.newChannel(content);
    final FileOutputStream fos = new FileOutputStream(targetFile);

    ////////////////////////////////////////////////////////////////////////////////
    // Do the downloading.
    ////////////////////////////////////////////////////////////////////////////////

    final long expectedSize = entity.getContentLength();
    System.out.println("===========================================================");
    System.out.println("Downloading " + sourceUri.toString());
    if (expectedSize < 0) {
        try {/*from   w  w w  .j a  va  2s. c o  m*/
            System.out.println("Unknown size.");
            IOUtils.copy(content, fos);
        } finally {
            // close http network connection
            content.close();
        }
    } else {
        long transferedSize = 0L;
        if (expectedSize > 1014 * 1024) {
            System.out.println("Expected size: " + (expectedSize / 1024 / 1024) + "MB");
        } else {
            System.out.println("Expected size: " + (expectedSize / 1024) + "KB");
        }
        final ProgressBar progressBar = new ProgressBar(expectedSize);
        while (transferedSize < expectedSize) {
            transferedSize += fos.getChannel().transferFrom(rbc, transferedSize, 1 << 20);
            progressBar.updateProgress(transferedSize);
        }
        fos.close();
        System.out.println();
    }
    System.out.println("Finished downloading.");
    System.out.println("===========================================================");
}

From source file:com.servoy.j2db.util.Utils.java

public static boolean writeTXTFile(File f, String content, Charset charset) {
    if (f != null) {
        FileOutputStream fos = null;
        try {/*from www.j  av a2s  . com*/
            fos = new FileOutputStream(f);
            FileChannel fc = fos.getChannel();
            ByteBuffer bb = charset.encode(content);
            fc.write(bb);
            bb.rewind();
            return true;
        } catch (Exception e) {
            Debug.error("Error writing txt file: " + f, e); //$NON-NLS-1$
        } finally {
            closeOutputStream(fos);
        }
    }
    return false;
}