Example usage for java.io FileInputStream getChannel

List of usage examples for java.io FileInputStream getChannel

Introduction

In this page you can find the example usage for java.io FileInputStream getChannel.

Prototype

public FileChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.FileChannel FileChannel object associated with this file input stream.

Usage

From source file:org.apache.beam.sdk.io.LocalFileSystem.java

@Override
protected ReadableByteChannel open(LocalResourceId resourceId) throws IOException {
    LOG.debug("opening file {}", resourceId);
    @SuppressWarnings("resource") // The caller is responsible for closing the channel.
    FileInputStream inputStream = new FileInputStream(resourceId.getPath().toFile());
    // Use this method for creating the channel (rather than new FileChannel) so that we get
    // regular FileNotFoundException. Closing the underyling channel will close the inputStream.
    return inputStream.getChannel();
}

From source file:org.h819.commons.file.MyPDFUtilss.java

/**
 *  PdfReader ? pdf  pdf ??//from  ww  w  .  j a  va  2s .  c  o m
 *
 * @param pdfFile       ? pdf 
 * @param ownerPassword ?
 * @return
 * @throws IOException
 */
public static PdfReader getPdfReader(File pdfFile, String ownerPassword) throws IOException {

    FileInputStream fileStream = new FileInputStream(pdfFile);

    if (ownerPassword == null)
        return getPdfReader(pdfFile);

    return new PdfReader(
            new RandomAccessFileOrArray(new FileChannelRandomAccessSource(fileStream.getChannel())),
            ownerPassword.getBytes());
}

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 w  w.j  a v  a  2s.  c o 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:org.paxle.crawler.fs.impl.FsCrawler.java

private File copyChanneled(final File file, final ICrawlerDocument cdoc, final boolean useFsync) {
    logger.info(String.format("Copying '%s' using the copy mechanism of the OS%s", file,
            (useFsync) ? " with fsync" : ""));

    final ITempFileManager tfm = this.contextLocal.getCurrentContext().getTempFileManager();
    if (tfm == null) {
        cdoc.setStatus(ICrawlerDocument.Status.UNKNOWN_FAILURE,
                "Cannot access ITempFileMananger from " + Thread.currentThread().getName());
        return null;
    }//from   www . j av a 2s  .  c om

    FileInputStream fis = null;
    FileOutputStream fos = null;
    File out = null;
    try {
        out = tfm.createTempFile();
        fis = new FileInputStream(file);
        fos = new FileOutputStream(out);

        final FileChannel in_fc = fis.getChannel();
        final FileChannel out_fc = fos.getChannel();

        long txed = 0L;
        while (txed < in_fc.size())
            txed += in_fc.transferTo(txed, in_fc.size() - txed, out_fc);

        if (useFsync)
            out_fc.force(false);
        out_fc.close();

        try {
            detectFormats(cdoc, fis);
        } catch (IOException ee) {
            logger.warn(
                    String.format("Error detecting format of '%s': %s", cdoc.getLocation(), ee.getMessage()));
        }
    } catch (IOException e) {
        logger.error(String.format("Error copying '%s' to '%s': %s", cdoc.getLocation(), out, e.getMessage()),
                e);
        cdoc.setStatus(ICrawlerDocument.Status.UNKNOWN_FAILURE, e.getMessage());
    } finally {
        if (fis != null)
            try {
                fis.close();
            } catch (IOException e) {
                /* ignore */}
        if (fos != null)
            try {
                fos.close();
            } catch (IOException e) {
                /* ignore */}
    }
    return out;
}

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;
    }//  w ww .  j  a v  a  2  s  .  c o  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:nl.nn.adapterframework.jdbc.JdbcFacade.java

protected void applyParameters(PreparedStatement statement, ParameterValueList parameters)
        throws SQLException, SenderException {
    // statement.clearParameters();

    /*/*from  w  ww . ja  v  a 2s  . com*/
          // getParameterMetaData() is not supported on the WebSphere java.sql.PreparedStatement implementation.
          int senderParameterCount = parameters.size();
          int statementParameterCount = statement.getParameterMetaData().getParameterCount();
          if (statementParameterCount<senderParameterCount) {
             throw new SenderException(getLogPrefix()+"statement has more ["+statementParameterCount+"] parameters defined than sender ["+senderParameterCount+"]");
          }
    */

    for (int i = 0; i < parameters.size(); i++) {
        ParameterValue pv = parameters.getParameterValue(i);
        String paramType = pv.getDefinition().getType();
        Object value = pv.getValue();
        //      log.debug("applying parameter ["+(i+1)+","+parameters.getParameterValue(i).getDefinition().getName()+"], value["+parameterValue+"]");

        if (Parameter.TYPE_DATE.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.DATE);
            } else {
                statement.setDate(i + 1, new java.sql.Date(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_DATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIMESTAMP.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_TIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIME);
            } else {
                statement.setTime(i + 1, new java.sql.Time(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_XMLDATETIME.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i + 1, new Timestamp(((Date) value).getTime()));
            }
        } else if (Parameter.TYPE_NUMBER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.NUMERIC);
            } else {
                statement.setDouble(i + 1, ((Number) value).doubleValue());
            }
        } else if (Parameter.TYPE_INTEGER.equals(paramType)) {
            if (value == null) {
                statement.setNull(i + 1, Types.INTEGER);
            } else {
                statement.setInt(i + 1, (Integer) value);
            }
        } else if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) {
            if (value instanceof FileInputStream) {
                FileInputStream fis = (FileInputStream) value;
                long len = 0;
                try {
                    len = fis.getChannel().size();
                } catch (IOException e) {
                    log.warn(getLogPrefix() + "could not determine file size", e);
                }
                statement.setBinaryStream(i + 1, fis, (int) len);
            } else if (value instanceof ByteArrayInputStream) {
                ByteArrayInputStream bais = (ByteArrayInputStream) value;
                long len = bais.available();
                statement.setBinaryStream(i + 1, bais, (int) len);
            } else {
                throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass()
                        + "] for parameter [" + pv.getDefinition().getName() + "]");
            }
        } else if ("string2bytes".equals(paramType)) {
            statement.setBytes(i + 1, ((String) value).getBytes());
        } else if ("bytes".equals(paramType)) {
            statement.setBytes(i + 1, (byte[]) value);
        } else {
            statement.setString(i + 1, (String) value);
        }
    }
}

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

/**
 * In case of interrupted, written file is not deleted.
 *///from  w w  w.ja va2  s.  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.jtransforms.fft.DoubleFFT_1DTest.java

/**
 * Read the binary reference data files generated with FFTW. The structure
 * of these files is very simple: double values are written linearly (little
 * endian).//  www . j a  va 2s .co m
 *
 * @param name
 *             the file name
 * @param data
 *             the array to be updated with the data read (the size of this
 *             array gives the number of <code>double</code> to be retrieved
 */
public void readData(final String name, final double[] data) {
    try {
        final File f = new File(getClass().getClassLoader().getResource(name).getFile());
        final FileInputStream fin = new FileInputStream(f);
        final FileChannel fc = fin.getChannel();
        final ByteBuffer buffer = ByteBuffer.allocate(8 * data.length);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        fc.read(buffer);
        for (int i = 0; i < data.length; i++) {
            data[i] = buffer.getDouble(8 * i);
        }
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:org.jtransforms.fft.DoubleFFT_1DTest.java

/**
 * Read the binary reference data files generated with FFTW. The structure
 * of these files is very simple: double values are written linearly (little
 * endian).//ww w  . j a v a  2 s  . c  o m
 *
 * @param name
 *             the file name
 * @param data
 *             the array to be updated with the data read (the size of this
 *             array gives the number of <code>double</code> to be retrieved
 */
public void readData(final String name, final DoubleLargeArray data) {
    try {
        final File f = new File(getClass().getClassLoader().getResource(name).getFile());
        final FileInputStream fin = new FileInputStream(f);
        final FileChannel fc = fin.getChannel();
        final ByteBuffer buffer = ByteBuffer.allocate(8 * (int) data.length());
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        fc.read(buffer);
        for (int i = 0; i < data.length(); i++) {
            data.setDouble(i, buffer.getDouble(8 * i));
        }
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

/**
 * Creates a new ServerClassLoader//  w  w  w.j  av a  2  s  .co m
 * @param parent The parent class loader
 * @param localCacheDirectory The directory to cache files to
 * @param remoteServer The URL of the remote server
 */
public ServerClassLoader(ClassLoader parent, File localCacheDirectory, URL remoteServer) {
    super(parent);
    this.localCacheDirectory = localCacheDirectory;
    this.localLibDirectory = new File(localCacheDirectory, LIB_DIR);
    File versionFile = new File(localCacheDirectory, "Version");
    boolean versionCorrect = false;
    if (!localCacheDirectory.exists()) {
        localCacheDirectory.mkdirs();
    } else {
        if (versionFile.exists()) {
            try {
                BufferedReader reader = new BufferedReader(new FileReader(versionFile));
                String version = reader.readLine();
                reader.close();
                versionCorrect = Defaults.PAG_VERSION.equals(version);
                log.info(version + " == " + Defaults.PAG_VERSION + " = " + versionCorrect);
            } catch (IOException e) {
                // Do Nothing
            }
        }
        try {
            FileInputStream input = new FileInputStream(new File(localCacheDirectory, INDEX));
            DataInputStream cacheFile = new DataInputStream(input);
            FileChannel channel = input.getChannel();
            while (channel.position() < channel.size()) {
                URL url = new URL(cacheFile.readUTF());
                String file = cacheFile.readUTF();
                if (versionCorrect && url.getHost().equals(remoteServer.getHost())
                        && (url.getPort() == remoteServer.getPort())) {
                    File jar = new File(localCacheDirectory, file);
                    if (jar.exists()) {
                        indexJar(url, jar);
                        CHECKED.put(url, true);
                    }
                }
            }
            input.close();
        } catch (FileNotFoundException e) {
            // Do Nothing - cache will be recreated later

        } catch (IOException e) {
            // Do Nothing - as above

        }
    }
    localLibDirectory.mkdirs();
    try {
        PrintWriter writer = new PrintWriter(versionFile);
        writer.println(Defaults.PAG_VERSION);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.remoteServer = remoteServer;
}