Example usage for java.nio.channels ReadableByteChannel close

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

Introduction

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

Prototype

public void close() throws IOException;

Source Link

Document

Closes this channel.

Usage

From source file:com.flexive.shared.FxFileUtils.java

/**
 * Copy the content of an InputStream to a file
 *
 * @param expectedSize    expected size of the stream
 * @param sourceStream    source/*ww  w.j a  va  2  s .com*/
 * @param destinationFile destination
 * @return copy was successful and sizes match
 */
public static boolean copyStream2File(long expectedSize, InputStream sourceStream, File destinationFile) {
    ReadableByteChannel sourceChannel = null;
    FileChannel destinationChannel = null;
    try {
        sourceChannel = Channels.newChannel(sourceStream);
        destinationChannel = new FileOutputStream(destinationFile).getChannel();
        return copyNIOChannel(sourceChannel, destinationChannel) == expectedSize
                && destinationFile.length() == expectedSize;
    } catch (IOException e) {
        LOG.error(e, e);
        return false;
    } finally {
        try {
            if (sourceChannel != null)
                sourceChannel.close();
        } catch (IOException e) {
            LOG.error(e);
        }
        try {
            if (destinationChannel != null)
                destinationChannel.close();
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

public static void streamCopy(InputStream streamIn, OutputStream streamOut, boolean leaveOutputOpen)
        throws IOException {
    ReadableByteChannel input = Channels.newChannel(streamIn);
    WritableByteChannel output = Channels.newChannel(streamOut);

    ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);

    while (input.read(buffer) != -1) {
        buffer.flip();//w w w. j a  v  a 2s. c om

        output.write(buffer);

        buffer.compact();
    }

    buffer.flip();

    // Make sure the buffer is empty
    while (buffer.hasRemaining()) {
        output.write(buffer);
    }

    input.close();
    if (!leaveOutputOpen) {
        output.close();
    }
}

From source file:it.unimi.di.big.mg4j.index.DiskBasedIndex.java

/** Commodity method for loading a big list of binary longs with specified endianness into a {@linkplain LongBigArrays long big array}.
 * //  w  w  w  .ja  va  2s. c o m
 * @param ioFactory the factory that will be used to perform I/O.
 * @param filename the file containing the longs.
 * @param byteOrder the endianness of the longs.
 * @return a big list of longs containing the longs in <code>file</code>.
 */
public static LongBigArrayBigList loadLongBigList(final IOFactory ioFactory, final CharSequence filename,
        final ByteOrder byteOrder) throws IOException {
    final long length = ioFactory.length(filename.toString()) / (Long.SIZE / Byte.SIZE);
    ReadableByteChannel channel = ioFactory.getReadableByteChannel(filename.toString());
    final LongBigArrayBigList loadLongBigList = loadLongBigList(channel, length, byteOrder);
    channel.close();
    return loadLongBigList;

}

From source file:net.vexelon.myglob.utils.Utils.java

/**
 * Reads an input stream into a byte array
 * @param source//from  w  w w  .j a  v a 2  s  . co m
 * @return Byte array of input stream data
 * @throws IOException
 */
public static byte[] read(InputStream source) throws IOException {
    ReadableByteChannel srcChannel = Channels.newChannel(source);
    ByteArrayOutputStream baos = new ByteArrayOutputStream(
            source.available() > 0 ? source.available() : BUFFER_PAGE_SIZE);
    WritableByteChannel destination = Channels.newChannel(baos);

    try {
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_PAGE_SIZE);
        while (srcChannel.read(buffer) > 0) {
            buffer.flip();
            while (buffer.hasRemaining()) {
                destination.write(buffer);
            }
            buffer.clear();
        }
        return baos.toByteArray();
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (srcChannel != null)
                srcChannel.close();
        } catch (IOException e) {
        }
        try {
            if (source != null)
                source.close();
        } catch (IOException e) {
        }
        try {
            if (destination != null)
                destination.close();
        } catch (IOException e) {
        }
    }
}

From source file:rascal.object.AbstractObjectFactory.java

public GitObject createObject(String name) throws IOException, CorruptedObjectException {
    ReadableByteChannel channel = getChannel(name);
    byte[] buffer = new byte[OBJECT_HEADER_BUFFER_LENGTH];
    channel.read(ByteBuffer.wrap(buffer));
    channel.close();
    int headerSpaceIndex;
    int headerEndIndex;
    if ((headerSpaceIndex = ArrayUtils.indexOf(buffer, (byte) ' ')) == ArrayUtils.INDEX_NOT_FOUND
            || (headerEndIndex = ArrayUtils.indexOf(buffer, (byte) 0)) == ArrayUtils.INDEX_NOT_FOUND
            || headerSpaceIndex >= headerEndIndex) {
        throw new CorruptedObjectException(name, "Corrupted object header");
    }/*from w  w  w.  j  a va  2  s  . c o  m*/
    try {
        return createObject(name, buffer, headerSpaceIndex, headerEndIndex);
    } catch (UnknownObjectTypeException e) {
        throw new CorruptedObjectException(name, e);
    } catch (NumberFormatException e) {
        throw new CorruptedObjectException(name, e);
    }
}

From source file:com.thinkberg.moxo.vfs.s3.jets3t.Jets3tFileObject.java

protected void doAttach() throws Exception {
    if (!attached) {
        try {/*from  ww w.j  ava 2s  .  co  m*/
            object = service.getObject(bucket, getS3Key());
            System.err.println("Attached file to S3 Object: " + object);
            InputStream is = object.getDataInputStream();
            if (object.getContentLength() > 0) {
                ReadableByteChannel rbc = Channels.newChannel(is);
                FileChannel cacheFc = getCacheFileChannel();
                cacheFc.transferFrom(rbc, 0, object.getContentLength());
                cacheFc.close();
                rbc.close();
            } else {
                is.close();
            }
        } catch (S3ServiceException e) {
            object = new S3Object(bucket, getS3Key());
            object.setLastModifiedDate(new Date());
            System.err.println("Attached file to new S3 Object: " + object);
        }
        attached = true;
    }
}

From source file:de.Keyle.MyPet.util.Updater.java

public void download() {
    String url = "https://mypet-plugin.de/download/" + plugin + "/";
    if (MyPetVersion.isDevBuild()) {
        url += "dev";
    } else {/*ww  w .  ja  va 2s . c  o  m*/
        url += "release";
    }
    File pluginFile;
    if (Configuration.Update.REPLACE_OLD) {
        pluginFile = new File(MyPetApi.getPlugin().getFile().getParentFile().getAbsolutePath(),
                "update/" + MyPetApi.getPlugin().getFile().getName());
    } else {
        pluginFile = new File(MyPetApi.getPlugin().getFile().getParentFile().getAbsolutePath(),
                "update/MyPet-" + latest.getVersion() + ".jar");
    }

    String finalUrl = url;
    thread = new Thread(() -> {
        try {
            MyPetApi.getLogger().info(ChatColor.RED + "Start update download: " + ChatColor.RESET + latest);
            URL website = new URL(finalUrl);
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            FileOutputStream fos = new FileOutputStream(pluginFile);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
            rbc.close();
            String message = "Finished update download.";
            if (Configuration.Update.REPLACE_OLD || MyPetApi.getPlugin().getFile().getName()
                    .equals("MyPet-" + latest.getVersion() + ".jar")) {
                message += " The update will be loaded on the next server start.";
            } else {
                message += " The file was stored in the \"update\" folder.";
            }
            MyPetApi.getLogger().info(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
    thread.start();
}

From source file:com.slytechs.capture.FileFactory.java

public FormatType formatType(final File file) throws IOException {

    try {/*from w  w  w.  ja  v  a2s.  c  o m*/
        new PcapFileCapture(file, FileMode.ReadOnlyNoMap, null).close();

        if (logger.isTraceEnabled()) {
            logger.trace(file.getName() + ", type=" + FormatType.Pcap);
        }

        return FormatType.Pcap;
    } catch (final Exception e) {
    }

    try {
        new SnoopFileCapture(file, FileMode.ReadOnlyNoMap, null).close();

        if (logger.isTraceEnabled()) {
            logger.trace(file.getName() + ", type=" + FormatType.Pcap);
        }

        return FormatType.Snoop;
    } catch (final Exception e) {
    }

    /*
     * Now try InputCapture which may also yield a known format
     */
    ReadableByteChannel channel = new RandomAccessFile(file, "r").getChannel();
    FormatType type = formatType(channel);
    channel.close();

    if (logger.isTraceEnabled()) {
        logger.trace(file.getName() + ", type=" + FormatType.Pcap);
    }

    return type;
}

From source file:com.msr.dnsdemo.network.DownloadFile.java

public DownloadFile(final Context ctxt, String url, FileOutputStream out)
        throws IOException, NullPointerException {
    String version = "0.3.x";
    try {//from  ww  w . ja  v a  2  s  .c  o  m
        version = ctxt.getPackageManager().getPackageInfo("com.msr.dnsdemo", 0).versionName;
    } catch (NameNotFoundException e) {
    }

    httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter("http.useragent", USERAGENT + version);
    InputStream in = openURL(url);
    if (in == null) {
        Log.e(TAG, "Unable to download: " + url);
        return;
    }

    final ReadableByteChannel inputChannel = Channels.newChannel(in);
    final WritableByteChannel outputChannel = Channels.newChannel(out);

    try {
        Log.i(TAG, "Downloading " + url);
        fastChannelCopy(inputChannel, outputChannel);
    } finally {
        try {
            if (inputChannel != null) {
                inputChannel.close();
            }
            if (outputChannel != null) {
                outputChannel.close();
            }
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            if (e != null && e.getMessage() != null) {
                Log.e(TAG, e.getMessage());
            } else {
                Log.e(TAG, "fastChannelCopy() unknown error");
            }
        }
    }
}

From source file:info.lamatricexiste.network.Network.DownloadFile.java

public DownloadFile(final Context ctxt, String url, FileOutputStream out)
        throws IOException, NullPointerException {
    String version = "0.3.x";
    try {//from w  w  w  .ja va2 s  .  com
        version = ctxt.getPackageManager().getPackageInfo(ActivityMain.TAG, 0).versionName;
    } catch (NameNotFoundException e) {
    }

    httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter("http.useragent", USERAGENT + version);
    InputStream in = openURL(url);
    if (in == null) {
        Log.e(TAG, "Unable to download: " + url);
        return;
    }

    final ReadableByteChannel inputChannel = Channels.newChannel(in);
    final WritableByteChannel outputChannel = Channels.newChannel(out);

    try {
        Log.i(TAG, "Downloading " + url);
        fastChannelCopy(inputChannel, outputChannel);
    } finally {
        try {
            if (inputChannel != null) {
                inputChannel.close();
            }
            if (outputChannel != null) {
                outputChannel.close();
            }
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            if (e != null && e.getMessage() != null) {
                Log.e(TAG, e.getMessage());
            } else {
                Log.e(TAG, "fastChannelCopy() unknown error");
            }
        }
    }
}