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.wso2.carbon.mediation.library.service.upload.LibraryUploader.java

private void writeResource(DataHandler dataHandler, String tempDestPath, String destPath, String fileName)
        throws IOException {

    File tempDestFile = new File(tempDestPath, fileName);
    FileChannel out = null;/*w  w  w  .  j ava  2s .c  om*/
    FileChannel in = null;
    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(tempDestFile);
        dataHandler.writeTo(fos);
        fos.flush();

        /* File stream is copied to a temp directory in order handle hot deployment issue
           occurred in windows */
        dataHandler.writeTo(fos);
        out = new FileOutputStream(destPath + File.separator + fileName).getChannel();
        in = new FileInputStream(tempDestFile).getChannel();
        out.write(in.map(FileChannel.MapMode.READ_ONLY, 0, in.size()));
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            log.warn("Can't close file streams.", e);
        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            log.warn("Can't close file streams.", e);
        }
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            log.warn("Can't close file streams.", e);
        }
    }

    if (!tempDestFile.delete()) {
        if (log.isDebugEnabled()) {
            log.debug("temp file: " + tempDestFile.getAbsolutePath()
                    + " deletion failed, scheduled deletion on server exit.");
        }
        tempDestFile.deleteOnExit();
    }
}

From source file:org.gnucash.android.export.ExportAsyncTask.java

/**
 * Moves a file from <code>src</code> to <code>dst</code>
 * @param src Absolute path to the source file
 * @param dst Absolute path to the destination file
 * @throws IOException if the file could not be moved.
 *//*from www  . jav  a  2 s. com*/
public void moveFile(String src, String dst) throws IOException {
    File srcFile = new File(src);
    File dstFile = new File(dst);
    FileChannel inChannel = new FileInputStream(srcFile).getChannel();
    FileChannel outChannel = new FileOutputStream(dstFile).getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        outChannel.close();
    }
    srcFile.delete();
}

From source file:it.readbeyond.minstrel.commander.Commander.java

private void copyFile(String sourcePath, String destinationPath, final CallbackContext callbackContext) {
    String source = this.normalizePath(sourcePath);
    String destination = this.normalizePath(destinationPath);
    try {// w  w w .  j a v  a  2  s .  c  o  m
        File f = new File(source);
        if (f.exists()) {
            File d = new File(destination);

            // create parent directory, if not existing
            File destinationParent = d.getParentFile();
            destinationParent.mkdirs();

            // TODO check for write permission?
            // copy file
            FileInputStream inStream = new FileInputStream(f);
            FileOutputStream outStream = new FileOutputStream(d);
            FileChannel inChannel = inStream.getChannel();
            FileChannel outChannel = outStream.getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
            inStream.close();
            outStream.close();
            callbackContext.success(MESSAGE_FILE_COPIED);

        } else {
            callbackContext.success(MESSAGE_FILE_DOES_NOT_EXIST);
        }
    } catch (Exception e) {
        callbackContext.success(MESSAGE_ERROR_WHILE_COPYING);
    }
}

From source file:org.opennms.features.newts.converter.rrd.converter.JRobinConverter.java

public boolean moveFileSafely(final File in, final File out) throws IOException {
    FileInputStream fis = null;//from   w w  w.  j av  a 2 s . co  m
    FileOutputStream fos = null;
    FileChannel inChannel = null;
    FileChannel outChannel = null;
    final File tempOut = File.createTempFile("move", ".tmp");
    try {
        fis = new FileInputStream(in);
        fos = new FileOutputStream(tempOut);
        inChannel = fis.getChannel();
        outChannel = fos.getChannel();
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        try {
            if (inChannel != null)
                inChannel.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel);
        }
        try {
            if (outChannel != null)
                outChannel.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel);
        }
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis);
        }
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos);
        }
    }
    out.delete();
    if (!out.exists()) {
        tempOut.renameTo(out);
        return in.delete();
    }
    return false;
}

From source file:org.codehaus.preon.buffer.DefaultBitBuffer.java

/** Read byte buffer containing binary stream and set the bit pointer position to 0. */
public DefaultBitBuffer(String fileName) {

    File file = new File(fileName);

    // Open the file and then get a org.codehaus.preon.channel.channel from the stream
    FileInputStream fis;/*from ww  w  .  j a v  a2 s .  c  o  m*/

    try {
        fis = new FileInputStream(file);

        FileChannel fc = fis.getChannel();

        // Get the file's size and then map it into memory
        int fileSize = (int) fc.size();
        ByteBuffer inputByteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);

        // Close the org.codehaus.preon.channel.channel and the stream
        fc.close();

        this.byteBuffer = inputByteBuffer;
        bitBufBitSize = ((long) (inputByteBuffer.capacity())) << 3;
        bitPos = 0;

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.multibit.file.FileHandler.java

public static void copyFile(File sourceFile, File destinationFile) throws IOException {
    if (!destinationFile.exists()) {
        destinationFile.createNewFile();
    }//from w ww.  ja  va 2s. co  m
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    FileChannel source = null;
    FileChannel destination = null;
    try {
        fileInputStream = new FileInputStream(sourceFile);
        source = fileInputStream.getChannel();
        fileOutputStream = new FileOutputStream(destinationFile);
        destination = fileOutputStream.getChannel();
        long transfered = 0;
        long bytes = source.size();
        while (transfered < bytes) {
            transfered += destination.transferFrom(source, 0, source.size());
            destination.position(transfered);
        }
    } finally {
        if (source != null) {
            source.close();
            source = null;
        } else if (fileInputStream != null) {
            fileInputStream.close();
            fileInputStream = null;
        }
        if (destination != null) {
            destination.close();
            destination = null;
        } else if (fileOutputStream != null) {
            fileOutputStream.flush();
            fileOutputStream.close();
        }
    }
}

From source file:com.android.mms.transaction.RetrieveTransaction.java

public int checkPduResult() {
    if (!mPduFile.exists()) {
        Log.e(MmsApp.TXN_TAG, "checkPduResult MMS Fail, no pduFile = " + mPduFile);
        return SmsManager.MMS_ERROR_UNSPECIFIED;
    }/*from  w w w. ja va 2  s  .  co  m*/
    FileChannel channel = null;
    FileInputStream fs = null;
    RetrieveConf retrieveConf;
    try {
        fs = new FileInputStream(mPduFile);
        channel = fs.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
        while ((channel.read(byteBuffer)) > 0) {
            // do nothing
            // System.out.println("reading");
        }
        final GenericPdu pdu = (new PduParser(byteBuffer.array(),
                PduParserUtil.shouldParseContentDisposition(mSubId))).parse();
        if (pdu == null || !(pdu instanceof RetrieveConf)) {
            Log.e(MmsApp.TXN_TAG, "checkPduResult: invalid parsed PDU");
            return SmsManager.MMS_ERROR_UNSPECIFIED;
        }
        retrieveConf = (RetrieveConf) pdu;
        byte[] messageId = retrieveConf.getMessageId();
        MmsLog.d(MmsApp.TXN_TAG, "checkPduResult retrieveConf.messageId = " + new String(messageId));

        // Store the downloaded message
        PduPersister persister = PduPersister.getPduPersister(mContext);
        Uri messageUri = persister.persist(pdu, Telephony.Mms.Inbox.CONTENT_URI, true/*createThreadId*/,
                true/*groupMmsEnabled*/, null/*preOpenedFiles*/);
        if (messageUri == null) {
            Log.e(MmsApp.TXN_TAG, "checkPduResult: can not persist message");
            return SmsManager.MMS_ERROR_UNSPECIFIED;
        }
        mMessageUri = messageUri.toString();
        // Update some of the properties of the message
        final ContentValues values = new ContentValues();
        values.put(Telephony.Mms.DATE, System.currentTimeMillis() / 1000L);
        values.put(Telephony.Mms.READ, 0);
        values.put(Telephony.Mms.SEEN, 0);
        String creator = ActivityThread.currentPackageName();
        if (!TextUtils.isEmpty(creator)) {
            values.put(Telephony.Mms.CREATOR, creator);
        }
        values.put(Telephony.Mms.SUBSCRIPTION_ID, mSubId);
        if (SqliteWrapper.update(mContext, mContext.getContentResolver(), messageUri, values, null/*where*/,
                null/*selectionArg*/) != 1) {
            Log.e(MmsApp.TXN_TAG, "persistIfRequired: can not update message");
        }
        // Delete the corresponding NotificationInd
        SqliteWrapper.delete(mContext, mContext.getContentResolver(), Telephony.Mms.CONTENT_URI,
                LOCATION_SELECTION,
                new String[] { Integer.toString(PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND), mContentLocation });
        return Activity.RESULT_OK;
    } catch (IOException e) {
        e.printStackTrace();
        return SmsManager.MMS_ERROR_UNSPECIFIED;
    } catch (MmsException e) {
        e.printStackTrace();
        return SmsManager.MMS_ERROR_UNSPECIFIED;
    } catch (SQLiteException e) {
        e.printStackTrace();
        return SmsManager.MMS_ERROR_UNSPECIFIED;
    } catch (RuntimeException e) {
        e.printStackTrace();
        return SmsManager.MMS_ERROR_UNSPECIFIED;
    } finally {
        if (mPduFile != null) {
            mPduFile.delete();
        }
        try {
            if (channel != null) {
                channel.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (fs != null) {
                fs.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.etudes.jforum.view.install.InstallAction.java

private void copyFile(String from, String to) throws Exception {
    FileChannel source = new FileInputStream(new File(from)).getChannel();
    FileChannel dest = new FileOutputStream(new File(to)).getChannel();

    source.transferTo(0, source.size(), dest);
    source.close();//from w  w w. j a v a  2 s  . co m
    dest.close();
}

From source file:org.gephi.ui.components.ReportSelection.java

public void copy(File source, File dest) throws IOException {
    FileChannel in = null, out = null;
    try {/*from  w  w  w . j  av a2s  .c o  m*/
        if (dest.isDirectory()) {
            dest = new File(dest, source.getName());
        }
        in = new FileInputStream(source).getChannel();
        out = new FileOutputStream(dest).getChannel();

        long size = in.size();
        MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);

        out.write(buf);

    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:org.fhcrc.cpl.viewer.quant.gui.QuantitationReviewer.java

/**
 * Remove all the events the user has designated as 'bad' from the pepXML file they came from
 * TODO: report how many events weren't found
 * @param quantEvents/*from  ww  w . j  a  va  2  s  .co m*/
 * @param pepXmlFile
 * @param outFile
 * @throws IOException
 * @throws XMLStreamException
 */
public static void filterBadEventsFromFile(List<QuantEvent> quantEvents, File pepXmlFile, File outFile)
        throws IOException, XMLStreamException {
    Map<String, List<Integer>> fractionBadQuantScanListMap = new HashMap<String, List<Integer>>();
    Map<String, List<Integer>> fractionBadIDScanListMap = new HashMap<String, List<Integer>>();
    Map<String, Map<Integer, Float>> fractionScanNewRatioMap = new HashMap<String, Map<Integer, Float>>();

    for (QuantEvent quantEvent : quantEvents) {
        String fraction = quantEvent.getFraction();

        if (quantEvent.getIdCurationStatus() == QuantEvent.CURATION_STATUS_BAD) {
            List<Integer> thisFractionList = fractionBadIDScanListMap.get(fraction);
            if (thisFractionList == null) {
                thisFractionList = new ArrayList<Integer>();
                fractionBadIDScanListMap.put(fraction, thisFractionList);
            }
            thisFractionList.add(quantEvent.getScan());
            for (QuantEvent otherEvent : quantEvent.getOtherEvents())
                if (!thisFractionList.contains(otherEvent.getScan()))
                    thisFractionList.add(otherEvent.getScan());
            _log.debug("Stripping ID for " + (quantEvent.getOtherEvents().size() + 1) + " events for peptide "
                    + quantEvent.getPeptide() + " from fraction " + fraction);
        }
        //only if the ID was unknown or good do we check quant -- quant is automatically
        //filtered for bad IDs
        else if (quantEvent.getQuantCurationStatus() == QuantEvent.CURATION_STATUS_BAD) {
            List<Integer> thisFractionList = fractionBadQuantScanListMap.get(fraction);
            if (thisFractionList == null) {
                thisFractionList = new ArrayList<Integer>();
                fractionBadQuantScanListMap.put(fraction, thisFractionList);
            }
            thisFractionList.add(quantEvent.getScan());
            int numOtherEvents = 0;
            if (quantEvent.getOtherEvents() != null) {
                for (QuantEvent otherEvent : quantEvent.getOtherEvents())
                    if (!thisFractionList.contains(otherEvent.getScan()))
                        thisFractionList.add(otherEvent.getScan());
                numOtherEvents = quantEvent.getOtherEvents().size();
            }
            ApplicationContext.infoMessage("Stripping Quantitation for " + (numOtherEvents + 1)
                    + " events for peptide " + quantEvent.getPeptide() + " from fraction " + fraction);
        }
        //dhmay adding 20090723
        else if (quantEvent.getQuantCurationStatus() == QuantEvent.CURATION_STATUS_RATIO_ONEPEAK) {
            Map<Integer, Float> thisFractionMap = fractionScanNewRatioMap.get(fraction);
            if (thisFractionMap == null) {
                thisFractionMap = new HashMap<Integer, Float>();
                fractionScanNewRatioMap.put(fraction, thisFractionMap);
            }
            float newRatio = quantEvent.getRatioOnePeak();
            thisFractionMap.put(quantEvent.getScan(), newRatio);
            for (QuantEvent otherEvent : quantEvent.getOtherEvents())
                if (!thisFractionMap.containsKey(otherEvent.getScan()))
                    thisFractionMap.put(otherEvent.getScan(), newRatio);
            ApplicationContext.infoMessage(
                    "Changing ratios to " + newRatio + " for " + (quantEvent.getOtherEvents().size() + 1)
                            + " events for peptide " + quantEvent.getPeptide() + " from fraction " + fraction);
        }
    }
    ApplicationContext.infoMessage("OK, decided what to do.  Now to strip the IDs from the pepXML file....");
    File actualOutFile = outFile;
    String dummyOwner = "DUMMY_OWNER_QURATE_STRIP";
    boolean sameInputAndOutput = pepXmlFile.getAbsolutePath().equals(outFile.getAbsolutePath());
    if (sameInputAndOutput)
        actualOutFile = TempFileManager.createTempFile("temp_quratestrip_" + outFile.getName(), dummyOwner);

    StripQuantOrIDPepXmlRewriter quantStripper = new StripQuantOrIDPepXmlRewriter(pepXmlFile, actualOutFile,
            fractionBadIDScanListMap, fractionBadQuantScanListMap, fractionScanNewRatioMap);
    quantStripper.rewrite();
    quantStripper.close();
    if (sameInputAndOutput) {
        //file-copying.  Java 1.6 still doesn't have a reasonable and concise way to do it.
        FileChannel inChannel = new FileInputStream(actualOutFile).getChannel();
        FileChannel outChannel = new FileOutputStream(outFile).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            throw e;
        } finally {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
        TempFileManager.deleteTempFiles(dummyOwner);
    }
    ApplicationContext.infoMessage("Done!  Saved stripped file to " + outFile.getAbsolutePath());
}