Example usage for java.nio.channels FileChannel size

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

Introduction

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

Prototype

public abstract long size() throws IOException;

Source Link

Document

Returns the current size of this channel's file.

Usage

From source file:net.librec.util.FileUtil.java

/**
 * fast file copy//from w w w. j ava  2s.co m
 *
 * @param source source file
 * @param target target file
 * @throws Exception if error occurs
 */
public static void copyFile(File source, File target) throws Exception {

    FileInputStream fis = new FileInputStream(source);
    FileOutputStream fos = new FileOutputStream(target);
    FileChannel inChannel = fis.getChannel();
    FileChannel outChannel = fos.getChannel();

    // inChannel.transferTo(0, inChannel.size(), outChannel);
    // original -- apparently has trouble copying large files on Windows

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

    inChannel.close();
    outChannel.close();
    fis.close();
    fos.close();
}

From source file:org.squidy.designer.components.pdf.PDFPane.java

public PDFPane(String pdfFileLoc) {
    super();//  ww w  .  j  a v a  2 s  .c  om
    try {
        // load a pdf from a byte buffer
        File file = new File(pdfFileLoc);
        RandomAccessFile raf = new RandomAccessFile(file, "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
        PDFFile pdffile = new PDFFile(buf);
        pdfComponents = new PagePanel[pdffile.getNumPages()];
        pageHeight = (int) pdffile.getPage(0).getHeight() + 3;
        pageWidth = (int) pdffile.getPage(0).getWidth() + 1;

        for (int i = 0; i < pdfComponents.length; i++) {
            PagePanel p = new PagePanel();
            p.setBackground(Color.BLACK);
            p.setPreferredSize(new Dimension(pageWidth, pageHeight));
            PSwing ps = new PSwing(p);

            ps.setOffset(0, i * pageHeight);
            addChild(ps);
            p.showPage(pdffile.getPage(i));
        }
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Error in " + PDFPane.class.getName() + ".", e);
        }
        System.out.println(e.getMessage());
    }
}

From source file:org.ros.internal.message.new_style.ServiceLoader.java

private void addServiceDefinitionFromPaths(File searchPath, File servicePath, CharsetDecoder decoder)
        throws IOException {
    FileInputStream inputStream = new FileInputStream(servicePath);
    FileChannel channel = inputStream.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
    channel.read(buffer);/*from  ww w  . j a v  a 2s .com*/
    buffer.rewind();
    decoder.reset();
    String definition = decoder.decode(buffer).toString().trim();
    serviceDefinitions.put(pathToServiceName(searchPath, servicePath), definition);
    channel.close();
    inputStream.close();
}

From source file:org.lnicholls.galleon.util.Tools.java

public static InputStream getInputStream(File file) {
    try {/*from   w ww . j  ava  2 s.c o  m*/
        FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
        final ByteBuffer buf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) roChannel.size());
        return new InputStream() {
            public synchronized int read() throws IOException {
                if (!buf.hasRemaining()) {
                    return -1;
                }
                return buf.get();
            }

            public synchronized int read(byte[] bytes, int off, int len) throws IOException {
                if (!buf.hasRemaining()) {
                    return -1;
                }
                len = Math.min(len, buf.remaining());
                buf.get(bytes, off, len);
                return len;
            }
        };
    } catch (Exception ex) {
        Tools.logException(Tools.class, ex, file.getAbsolutePath());
    }
    return null;
}

From source file:org.ros.internal.message.new_style.MessageLoader.java

private void addMessageDefinitionFromPaths(File searchPath, File messagePath, CharsetDecoder decoder)
        throws IOException {
    FileInputStream inputStream = new FileInputStream(messagePath);
    FileChannel channel = inputStream.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
    channel.read(buffer);//from  w  w w .  j ava 2s .c  o m
    buffer.rewind();
    decoder.reset();
    String definition = decoder.decode(buffer).toString().trim();
    messageDefinitions.put(pathToMessageName(searchPath, messagePath), definition);
    channel.close();
    inputStream.close();
}

From source file:ome.services.blitz.repo.RepoRawFileStoreI.java

public void truncate_async(AMD_RawFileStore_truncate __cb, long length, Current __current) throws ServerError {

    if (true) {//from   w  ww . j ava  2  s  .co  m
        // See ticket:2562
        __cb.ice_exception(new omero.ApiUsageException(null, null, "Currently disabled."));
        return;
    }

    try {
        FileChannel fc = this.rafile.getChannel();
        if (fc.size() < length) {
            __cb.ice_response(false);
        } else {
            this.rafile.getChannel().truncate(length);
            __cb.ice_response(true);
        }
    } catch (Throwable t) {
        __cb.ice_exception(convert(t));
    }
}

From source file:org.lnicholls.galleon.util.Tools.java

public static BufferedImage ImageIORead(File file) {
    System.gc();//from w  w  w .  j a v  a2 s.  c o  m
    try {
        FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
        final ByteBuffer buf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) roChannel.size());
        return ImageIO.read(new InputStream() {
            public synchronized int read() throws IOException {
                if (!buf.hasRemaining()) {
                    return -1;
                }
                return buf.get();
            }

            public synchronized int read(byte[] bytes, int off, int len) throws IOException {
                if (!buf.hasRemaining()) {
                    return -1;
                }
                len = Math.min(len, buf.remaining());
                buf.get(bytes, off, len);
                return len;
            }
        });
    } catch (Exception ex) {
        Tools.logException(Tools.class, ex, file.getAbsolutePath());
    }

    try {
        return ImageIO.read(new FileInputStream(file));
    } catch (Exception ex) {
        Tools.logException(Tools.class, ex, file.getAbsolutePath());
    }
    return null;
}

From source file:Main.java

public static long findCentralDirStartOffset(final FileChannel fileChannel, final long commentLength)
        throws IOException {
    // End of central directory record (EOCD)
    // Offset    Bytes     Description[23]
    // 0           4       End of central directory signature = 0x06054b50
    // 4           2       Number of this disk
    // 6           2       Disk where central directory starts
    // 8           2       Number of central directory records on this disk
    // 10          2       Total number of central directory records
    // 12          4       Size of central directory (bytes)
    // 16          4       Offset of start of central directory, relative to start of archive
    // 20          2       Comment length (n)
    // 22          n       Comment
    // For a zip with no archive comment, the
    // end-of-central-directory record will be 22 bytes long, so
    // we expect to find the EOCD marker 22 bytes from the end.

    final ByteBuffer zipCentralDirectoryStart = ByteBuffer.allocate(4);
    zipCentralDirectoryStart.order(ByteOrder.LITTLE_ENDIAN);
    fileChannel.position(fileChannel.size() - commentLength - 6); // 6 = 2 (Comment length) + 4 (Offset of start of central directory, relative to start of archive)
    fileChannel.read(zipCentralDirectoryStart);
    final long centralDirStartOffset = zipCentralDirectoryStart.getInt(0);
    return centralDirStartOffset;
}

From source file:com.highcharts.export.util.SVGCreator.java

private String readFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try {/*w w w.j  a v a  2s  .  c o  m*/
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        /* Instead of using default, pass in a decoder. */
        return Charset.forName("utf-8").decode(bb).toString();
    } finally {
        stream.close();
    }
}

From source file:org.apache.nifi.file.FileUtils.java

public static long copyFile(final File source, final OutputStream stream, final boolean closeOutputStream,
        final boolean lockInputFile) throws FileNotFoundException, IOException {
    FileInputStream fis = null;// www  . j  a va  2  s .  c  o  m
    FileLock inLock = null;
    long fileSize = 0L;
    try {
        fis = new FileInputStream(source);
        final FileChannel in = fis.getChannel();
        if (lockInputFile) {
            inLock = in.tryLock(0, Long.MAX_VALUE, true);
            if (inLock == null) {
                throw new IOException("Unable to obtain exclusive file lock for: " + source.getAbsolutePath());
            }

        }

        byte[] buffer = new byte[1 << 18]; //256 KB
        int bytesRead = -1;
        while ((bytesRead = fis.read(buffer)) != -1) {
            stream.write(buffer, 0, bytesRead);
        }
        in.force(false);
        stream.flush();
        fileSize = in.size();
    } finally {
        FileUtils.releaseQuietly(inLock);
        FileUtils.closeQuietly(fis);
        if (closeOutputStream) {
            FileUtils.closeQuietly(stream);
        }
    }
    return fileSize;
}