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:org.oscarehr.document.web.ManageDocumentAction.java

public File createCacheVersion(Document d, int pageNum) throws Exception {

    File documentCacheDir = new File(EDocUtil.getCacheDirectory());
    File file = new File(EDocUtil.getDocumentPath(d.getDocfilename()));

    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);
    if (raf != null)
        raf.close();//www.  j a v a2s.  c  o m
    if (channel != null)
        channel.close();
    // draw the first page to an image
    PDFPage ppage = pdffile.getPage(pageNum);

    log.debug("WIDTH " + (int) ppage.getBBox().getWidth() + " height " + (int) ppage.getBBox().getHeight());

    // get the width and height for the doc at the default zoom
    Rectangle rect = new Rectangle(0, 0, (int) ppage.getBBox().getWidth(), (int) ppage.getBBox().getHeight());

    log.debug("generate the image");
    Image img = ppage.getImage(rect.width, rect.height, // width & height
            rect, // clip rect
            null, // null for the ImageObserver
            true, // fill background with white
            true // block until drawing is done
    );

    log.debug("about to Print to stream");
    File outfile = new File(documentCacheDir, d.getDocfilename() + "_" + pageNum + ".png");

    OutputStream outs = null;
    try {
        outs = new FileOutputStream(outfile);

        RenderedImage rendImage = (RenderedImage) img;
        ImageIO.write(rendImage, "png", outs);
        outs.flush();
    } finally {
        if (outs != null)
            outs.close();
    }
    return outfile;

}

From source file:com.splout.db.dnode.Fetcher.java

/**
 * In case of interrupted, written file is not deleted.
 *//*from  ww  w  .jav a2s  .co m*/
private void copyFile(File sourceFile, File destFile, Reporter reporter)
        throws IOException, InterruptedException {
    if (!destFile.exists()) {
        destFile.createNewFile();
    }
    FileChannel source = null;
    FileChannel destination = null;

    Throttler throttler = new Throttler((double) bytesPerSecThrottle);

    FileInputStream iS = null;
    FileOutputStream oS = null;

    try {
        iS = new FileInputStream(sourceFile);
        oS = new FileOutputStream(destFile);
        source = iS.getChannel();
        destination = oS.getChannel();
        long bytesSoFar = 0;
        long reportingBytesSoFar = 0;
        long size = source.size();

        int transferred = 0;

        while (bytesSoFar < size) {
            // Needed to being able to be interrupted at any moment.
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            // Casting to int here is safe since we will transfer at most "downloadBufferSize" bytes.
            // This is done on purpose for being able to implement Throttling.
            transferred = (int) destination.transferFrom(source, bytesSoFar, downloadBufferSize);
            bytesSoFar += transferred;
            reportingBytesSoFar += transferred;
            throttler.incrementAndThrottle(transferred);
            if (reportingBytesSoFar >= bytesToReportProgress) {
                reporter.progress(reportingBytesSoFar);
                reportingBytesSoFar = 0l;
            }
        }

        if (reporter != null) {
            reporter.progress(reportingBytesSoFar);
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        if (iS != null) {
            iS.close();
        }
        if (oS != null) {
            oS.close();
        }
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:org.oscarehr.document.web.ManageDocumentAction.java

public ActionForward view2(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // TODO: NEED TO CHECK FOR ACCESS
    String doc_no = request.getParameter("doc_no");
    log.debug("Document No :" + doc_no);

    LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ, LogConst.CON_DOCUMENT,
            doc_no, request.getRemoteAddr());

    Document d = documentDAO.getDocument(doc_no);
    log.debug("Document Name :" + d.getDocfilename());

    // TODO: Right now this assumes it's a pdf which it shouldn't

    response.setContentType("image/png");
    // response.setHeader("Content-Disposition", "attachment;filename=\"" + filename+ "\"");
    // read the file name.
    File file = new File(EDocUtil.getDocumentPath(d.getDocfilename()));

    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);
    // draw the first page to an image
    PDFPage ppage = pdffile.getPage(0);/*from  w  w  w .j a v  a2  s  . co  m*/

    log.debug("WIDTH " + (int) ppage.getBBox().getWidth() + " height " + (int) ppage.getBBox().getHeight());

    // get the width and height for the doc at the default zoom
    Rectangle rect = new Rectangle(0, 0, (int) ppage.getBBox().getWidth(), (int) ppage.getBBox().getHeight());

    log.debug("generate the image");
    Image img = ppage.getImage(rect.width, rect.height, // width & height
            rect, // clip rect
            null, // null for the ImageObserver
            true, // fill background with white
            true // block until drawing is done
    );

    log.debug("about to Print to stream");
    ServletOutputStream outs = response.getOutputStream();

    RenderedImage rendImage = (RenderedImage) img;
    ImageIO.write(rendImage, "png", outs);
    outs.flush();
    outs.close();
    return null;
}

From source file:dk.netarkivet.common.utils.FileUtils.java

/**
 * Copy file from one location to another. Will silently overwrite an
 * already existing file.//from w w  w  .java2 s.c  o  m
 *
 * @param from
 *            original to copy
 * @param to
 *            destination of copy
 * @throws IOFailure if an io error occurs while copying file,
 * or the original file does not exist.
 */
public static void copyFile(File from, File to) {
    ArgumentNotValid.checkNotNull(from, "File from");
    ArgumentNotValid.checkNotNull(to, "File to");
    if (!from.exists()) {
        String errMsg = "Original file '" + from.getAbsolutePath() + "' does not exist";
        log.warn(errMsg);
        throw new IOFailure(errMsg);
    }
    try {
        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            inStream = new FileInputStream(from);
            outStream = new FileOutputStream(to);
            in = inStream.getChannel();
            out = outStream.getChannel();
            long bytesTransferred = 0;
            do {
                //Note: in.size() is called every loop, because if it should
                //change size, we might end up in an infinite loop trying to
                //copy more bytes than are actually available.
                bytesTransferred += in.transferTo(bytesTransferred,
                        Math.min(Constants.IO_CHUNK_SIZE, in.size() - bytesTransferred), out);
            } while (bytesTransferred < in.size());
        } finally {
            if (inStream != null) {
                inStream.close();
            }
            if (outStream != null) {
                outStream.close();
            }
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    } catch (IOException e) {
        final String errMsg = "Error copying file '" + from.getAbsolutePath() + "' to '" + to.getAbsolutePath()
                + "'";
        log.warn(errMsg, e);
        throw new IOFailure(errMsg, e);
    }
}

From source file:com.liferay.portal.util.FileImpl.java

public boolean isSameContent(File file, byte[] bytes, int length) {
    FileChannel fileChannel = null;

    try {//from  w  w w  .  j  a v  a2 s  .c o  m
        FileInputStream fileInputStream = new FileInputStream(file);

        fileChannel = fileInputStream.getChannel();

        if (fileChannel.size() != length) {
            return false;
        }

        byte[] buffer = new byte[1024];

        ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);

        int bufferIndex = 0;
        int bufferLength = -1;

        while (((bufferLength = fileChannel.read(byteBuffer)) > 0) && (bufferIndex < length)) {

            for (int i = 0; i < bufferLength; i++) {
                if (buffer[i] != bytes[bufferIndex++]) {
                    return false;
                }
            }

            byteBuffer.clear();
        }

        if ((bufferIndex != length) || (bufferLength != -1)) {
            return false;
        } else {
            return true;
        }
    } catch (Exception e) {
        return false;
    } finally {
        if (fileChannel != null) {
            try {
                fileChannel.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:eu.medsea.mimeutil.detector.OpendesktopMimeDetector.java

private void init(final String mimeCacheFile) {
    String cacheFile = mimeCacheFile;
    if (!new File(cacheFile).exists()) {
        cacheFile = internalMimeCacheFile;

    }//from  w  ww  .  j a v  a 2s  . c  om
    // Map the mime.cache file as a memory mapped file
    FileChannel rCh = null;
    try {
        RandomAccessFile raf = null;
        raf = new RandomAccessFile(cacheFile, "r");
        rCh = (raf).getChannel();
        content = rCh.map(FileChannel.MapMode.READ_ONLY, 0, rCh.size());

        // Read all of the MIME type from the Alias list
        initMimeTypes();

        if (log.isDebugEnabled()) {
            log.debug("Registering a FileWatcher for [" + cacheFile + "]");
        }
        TimerTask task = new FileWatcher(new File(cacheFile)) {
            protected void onChange(File file) {
                initMimeTypes();
            }
        };

        timer = new Timer();
        // repeat the check every 10 seconds
        timer.schedule(task, new Date(), 10000);

    } catch (Exception e) {
        throw new MimeException(e);
    } finally {
        if (rCh != null) {
            try {
                rCh.close();
            } catch (Exception e) {
                log.error(e.getLocalizedMessage(), e);
            }
        }
    }
}

From source file:edu.harvard.iq.dvn.ingest.dsb.DSBWrapper.java

public String ingest(StudyFileEditBean file) throws IOException {
    dbgLog.fine("***** DSBWrapper: ingest(): start *****\n");

    String ddi = null;/*from  w ww  .j a  v a2  s. c  o m*/

    BufferedInputStream infile = null;

    // ingest-source file
    File tempFile = new File(file.getTempSystemFileLocation());
    SDIOData sd = null;

    if (file.getControlCardSystemFileLocation() == null) {
        // A "classic", 1 file ingest:        

        String mime_type = file.getStudyFile().getFileType();

        infile = new BufferedInputStream(new FileInputStream(tempFile));

        dbgLog.info("\nfile mimeType=" + mime_type + "\n\n");

        // get available FileReaders for this MIME-type
        Iterator<StatDataFileReader> itr = StatDataIO.getStatDataFileReadersByMIMEType(mime_type);

        if (itr.hasNext()) {
            // use the first Subsettable data reader
            StatDataFileReader sdioReader = itr.next();

            dbgLog.info("reader class name=" + sdioReader.getClass().getName());

            if (mime_type != null) {
                String requestedCharacterEncoding = file.getDataLanguageEncoding();
                if (requestedCharacterEncoding != null) {
                    dbgLog.fine("Will try to process the file assuming that the character strings are "
                            + "encoded in " + requestedCharacterEncoding);
                    sdioReader.setDataLanguageEncoding(requestedCharacterEncoding);
                }
                sd = sdioReader.read(infile, null);
            } else {
                // fail-safe block if mime_type is null
                // check the format type again and then read the file
                dbgLog.info("mime-type was null: use the back-up method");
                sd = StatDataIO.read(infile, null);
            }
        } else {

            throw new IllegalArgumentException(
                    "No FileReader Class found" + " for this mime type=" + mime_type);
        }
    } else {
        // This is a 2-file ingest.
        // As of now, there are 2 supported methods: 
        // 1. CSV raw data file + SPSS control card;
        // 2. TAB raw data file + DDI control card;
        // NOTE, that "POR file with the Extended Labels" is NOT a 2-file.
        // control card-based ingest! Rather, we ingest the file as a regular
        // SPSS/POR dataset, then modify the variable labels in the resulting
        // TabularFile. 

        File rawDataFile = tempFile;

        infile = new BufferedInputStream(new FileInputStream(file.getControlCardSystemFileLocation()));

        String controlCardType = file.getControlCardType();

        if (controlCardType == null || controlCardType.equals("")) {
            dbgLog.info("No Control Card Type supplied.");

            throw new IllegalArgumentException("No Control Card Type supplied.");
        }

        Iterator<StatDataFileReader> itr = StatDataIO.getStatDataFileReadersByFormatName(controlCardType);

        if (!itr.hasNext()) {
            dbgLog.info("No FileReader class found for " + controlCardType + ".");

            throw new IllegalArgumentException("No FileReader Class found for " + controlCardType + ".");
        }

        StatDataFileReader sdioReader = itr.next();

        dbgLog.info("reader class name=" + sdioReader.getClass().getName());

        sd = sdioReader.read(infile, rawDataFile);

    }

    if (sd != null) {
        SDIOMetadata smd = sd.getMetadata();

        // tab-file: source file
        String tabDelimitedDataFileLocation = smd.getFileInformation().get("tabDelimitedDataFileLocation")
                .toString();

        dbgLog.fine("tabDelimitedDataFileLocation=" + tabDelimitedDataFileLocation);

        dbgLog.fine("data file(tempFile): abs path:\n" + file.getTempSystemFileLocation());
        dbgLog.fine("mimeType :\n" + file.getStudyFile().getFileType());

        if (infile != null) {
            infile.close();
        }

        // parse the response
        StudyFile f = file.getStudyFile();

        // first, check dir
        // create a sub-directory "ingested"
        File newDir = new File(tempFile.getParentFile(), "ingested");

        if (!newDir.exists()) {
            newDir.mkdirs();
        }
        dbgLog.fine("newDir: abs path:\n" + newDir.getAbsolutePath());

        // tab-file case: destination
        File newFile = new File(newDir, tempFile.getName());

        // nio-based file-copying idiom
        FileInputStream fis = new FileInputStream(tabDelimitedDataFileLocation);
        FileOutputStream fos = new FileOutputStream(newFile);
        FileChannel fcin = fis.getChannel();
        FileChannel fcout = fos.getChannel();
        fcin.transferTo(0, fcin.size(), fcout);
        fcin.close();
        fcout.close();
        fis.close();
        fos.close();

        dbgLog.fine("newFile: abs path:\n" + newFile.getAbsolutePath());

        // store the tab-file location
        file.setIngestedSystemFileLocation(newFile.getAbsolutePath());

        // finally, if we have an extended variable map, let's replace the 
        // labels that have been found in the data file: 

        if (file.getExtendedVariableLabelMap() != null) {
            for (String varName : file.getExtendedVariableLabelMap().keySet()) {
                if (smd.getVariableLabel().containsKey(varName)) {
                    smd.getVariableLabel().put(varName, file.getExtendedVariableLabelMap().get(varName));
                }
            }
        }

        // return xmlToParse;
        DDIWriter dw = new DDIWriter(smd);
        ddi = dw.generateDDI();

        return ddi;
    }
    return null;
}

From source file:org.t3.metamediamanager.MediaCenterDataMediaBrowser.java

/**
 * use for copy images given in an array in a folder given in parameters
 * @param images//ww w  .j  av a 2  s. com
 * @param newFileName
 */
public void copy_images(String images, String newFileName) {

    FileChannel in = null; // canal d'entre
    FileChannel out = null; // canal de sortie
    try {
        // Init
        in = new FileInputStream(images).getChannel();
        out = new FileOutputStream(newFileName).getChannel();

        // Copy in->out
        in.transferTo(0, in.size(), out);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

public void copyObject(String sourceBucket, String sourceObject, String destinationBucket,
        String destinationObject) throws IOException {
    File oldObjectFile = new File(
            rootDirectory + FILE_SEPARATOR + sourceBucket + FILE_SEPARATOR + sourceObject);
    File newObjectFile = new File(
            rootDirectory + FILE_SEPARATOR + destinationBucket + FILE_SEPARATOR + destinationObject);
    if (!oldObjectFile.equals(newObjectFile)) {
        FileInputStream fileInputStream = null;
        FileChannel fileIn = null;
        FileOutputStream fileOutputStream = null;
        FileChannel fileOut = null;
        try {/*from   w ww.  java 2  s.  com*/
            fileInputStream = new FileInputStream(oldObjectFile);
            fileIn = fileInputStream.getChannel();
            fileOutputStream = new FileOutputStream(newObjectFile);
            fileOut = fileOutputStream.getChannel();
            fileIn.transferTo(0, fileIn.size(), fileOut);
        } finally {
            if (fileIn != null)
                fileIn.close();
            if (fileInputStream != null)
                fileInputStream.close();
            if (fileOut != null)
                fileOut.close();
            if (fileOutputStream != null)
                fileOutputStream.close();
        }
    }
}

From source file:com.edgenius.wiki.service.impl.SitemapServiceImpl.java

private void appendSitemapIndex(String sitemap) throws IOException {
    File sitemapIndexFile = new File(mapResourcesRoot.getFile(), SITEMAP_INDEX_NAME);
    if (!sitemapIndexFile.exists()) {
        //if a new sitemap file
        List<String> lines = new ArrayList<String>();
        lines.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        lines.add("<sitemapindex xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
        lines.add("</sitemapindex>");
        FileUtils.writeLines(sitemapIndexFile, lines);
    }//  w w  w  .  j a  v  a2s .com

    RandomAccessFile rfile = new RandomAccessFile(sitemapIndexFile, "rw");
    FileChannel channel = rfile.getChannel();

    //this new content will append to end of file before XML end tag
    StringBuilder lines = new StringBuilder();
    lines.append("   <sitemap>\n");
    lines.append("     <loc>" + WebUtil.getHostAppURL() + SITEMAP_URL_CONTEXT + sitemap + "</loc>\n");
    lines.append("     <lastmod>" + TIME_FORMAT.format(new Date()) + " </lastmod>\n");
    lines.append("   </sitemap>\n");
    //the last tag will be overwrite, so append it again to new content. 
    lines.append(SITEMAP_INDEX_TAIL_FLAG);
    byte[] content = lines.toString().getBytes();

    ByteBuffer byteBuf = ByteBuffer.allocate(512);
    // seek first
    int len = 0, headIdx = 0;
    long tailIdx = channel.size() - 512;
    tailIdx = tailIdx < 0 ? 0 : tailIdx;

    long headPos = -1;
    StringBuilder header = new StringBuilder();
    while ((len = channel.read(byteBuf, tailIdx)) > 0) {
        byteBuf.rewind();
        byte[] dst = new byte[len];
        byteBuf.get(dst, 0, len);
        header.append(new String(dst, "UTF8"));
        headIdx = header.indexOf(SITEMAP_INDEX_TAIL_FLAG);
        if (headIdx != -1) {
            headPos = channel.size() - header.substring(headIdx).getBytes().length;
            break;
        }
    }
    FileLock lock = channel.tryLock(headPos, content.length, false);
    try {
        channel.write(ByteBuffer.wrap(content), headPos);
    } finally {
        lock.release();
    }

    channel.force(false);
    rfile.close();

}