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.apache.cordova.backgroundDownload.BackgroundDownload.java

private void copyFile(File src, File dest) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dest).getChannel();
    try {/* ww w.ja  v a2 s  .  c  om*/
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null) {
            inChannel.close();
        }
        if (outChannel != null) {
            outChannel.close();
        }
    }
}

From source file:interfazGrafica.frmMoverRFC.java

public void mostrarPDF() {
    String curp = "";
    curp = txtCapturaCurp.getText();/*from w w  w  .ja  v  a 2 s .  c o m*/
    ArrayList<DocumentoRFC> Docs = new ArrayList<>();
    DocumentoRFC sigExp;
    DocumentoRFC temporal;
    RFCescaneado tempo = new RFCescaneado();

    //tempo.borrartemporal();
    sigExp = expe.obtenerArchivosExp();
    Nombre_Archivo = sigExp.getNombre();
    nombreArchivo.setText(Nombre_Archivo);

    if (Nombre_Archivo != "") {
        doc = sigExp;
        System.out.println("Obtuvo el nombre del archivo.");
        System.out.println(doc.ruta + doc.nombre);
        String file = "C:\\escaneos\\Local\\Temporal\\" + doc.nombre;
        File arch = new File(file);
        System.out.println("Encontr el siguiente archivo:");
        System.out.println(file);
        System.out.println("");
        if (arch.exists()) {
            System.out.println("El archivo existe");
        }
        try {
            System.out.println("Entr al try");
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            System.out.println("Reconoc el archivo" + file);
            FileChannel channel = raf.getChannel();
            System.out.println("Se abrio el canal");
            ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
            System.out.println("Channel map");
            PDFFile pdffile = new PDFFile(buf);
            System.out.println("Creando un pdf file");
            PDFPage page = pdffile.getPage(0);
            System.out.println("Obteniendo la pagina con " + 0);

            panelpdf2.showPage(page);
            System.out.println("mostrando el panel pdf2");
            repaint();
            System.gc();

            buf.clear();
            raf.close();

            System.gc();

        } catch (Exception ioe) {
            JOptionPane.showMessageDialog(null, "Error al abrir el archivo");
            ioe.printStackTrace();
        }

    }
    // tempo.borrartemporal();
}

From source file:com.doplgangr.secrecy.FileSystem.File.java

public java.io.File readFile(CryptStateListener listener) {
    decrypting = true;//from   w  w w.  ja  va 2  s .c o m
    InputStream is = null;
    OutputStream out = null;
    java.io.File outputFile = null;
    try {
        outputFile = java.io.File.createTempFile("tmp" + name, "." + FileType, storage.getTempFolder());
        outputFile.mkdirs();
        outputFile.createNewFile();
        AES_Encryptor enc = new AES_Encryptor(key);
        is = new CipherInputStream(new FileInputStream(file), enc.decryptstream());
        listener.setMax((int) file.length());
        ReadableByteChannel inChannel = Channels.newChannel(is);
        FileChannel outChannel = new FileOutputStream(outputFile).getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(Config.bufferSize);
        while (inChannel.read(byteBuffer) >= 0 || byteBuffer.position() > 0) {
            byteBuffer.flip();
            outChannel.write(byteBuffer);
            byteBuffer.compact();
            listener.updateProgress((int) outChannel.size());
        }
        inChannel.close();
        outChannel.close();
        Util.log(outputFile.getName(), outputFile.length());
        return outputFile;
    } catch (FileNotFoundException e) {
        listener.onFailed(2);
        Util.log("Encrypted File is missing", e.getMessage());
    } catch (IOException e) {
        Util.log("IO Exception while decrypting", e.getMessage());
        if (e.getMessage().contains("pad block corrupted"))
            listener.onFailed(1);
        else
            e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        listener.Finished();
        decrypting = false;
        try {
            if (is != null) {
                is.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // An error occured. Too Bad
    if (outputFile != null)
        storage.purgeFile(outputFile);
    return null;
}

From source file:no.sesat.search.http.filters.SiteJspLoaderFilter.java

private void downloadJsp(final HttpServletRequest request, final String jsp) throws MalformedURLException {

    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();// ww  w . ja  va  2 s.c  o m

    byte[] golden = new byte[0];

    // search skins for the jsp and write it out to "golden"
    for (Site site = (Site) request.getAttribute(Site.NAME_KEY); 0 == golden.length; site = site.getParent()) {

        if (null == site) {
            if (null == config.getServletContext().getResource(jsp)) {
                throw new ResourceLoadException("Unable to find " + jsp + " in any skin");
            }
            break;
        }

        final Site finalSite = site;
        final BytecodeLoader bcLoader = UrlResourceLoader.newBytecodeLoader(finalSite.getSiteContext(), jsp,
                null);
        bcLoader.abut();
        golden = bcLoader.getBytecode();
    }

    // if golden now contains data save it to a local (ie local web application) file
    if (0 < golden.length) {
        try {
            final File file = new File(root + jsp);

            // create the directory structure
            file.getParentFile().mkdirs();

            // check existing file
            boolean needsUpdating = true;
            final boolean fileExisted = file.exists();
            if (!fileExisted) {
                file.createNewFile();
            }

            // channel.lock() only synchronises file access between programs, but not between threads inside
            //  the current JVM. The latter results in the OverlappingFileLockException.
            //  At least this is my current understanding of java.nio.channels
            //   It may be that no synchronisation or locking is required at all. A beer to whom answers :-)
            // So we must provide synchronisation between our own threads,
            //  synchronisation against the file's path (using the JVM's String.intern() functionality)
            //  should work. (I can't imagine this string be used for any other synchronisation purposes).
            synchronized (file.toString().intern()) {

                RandomAccessFile fileAccess = null;
                FileChannel channel = null;

                try {

                    fileAccess = new RandomAccessFile(file, "rws");
                    channel = fileAccess.getChannel();

                    channel.lock();

                    if (fileExisted) {

                        final byte[] bytes = new byte[(int) channel.size()];
                        final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
                        int reads;
                        do {
                            reads = channel.read(byteBuffer);
                        } while (0 < reads);

                        needsUpdating = !Arrays.equals(golden, bytes);
                    }

                    if (needsUpdating) {
                        // download file from skin
                        channel.write(ByteBuffer.wrap(golden), 0);
                        file.deleteOnExit();
                    }
                } finally {
                    if (null != channel) {
                        channel.close();
                    }
                    if (null != fileAccess) {
                        fileAccess.close();
                    }

                    LOG.debug("resource created as " + config.getServletContext().getResource(jsp));
                }
            }

        } catch (IOException ex) {
            LOG.error(ex.getMessage(), ex);
        }
    }

    stopWatch.stop();
    LOG.trace("SiteJspLoaderFilter.downloadJsp(..) took " + stopWatch);
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestFsck.java

public void testCorruptBlock() throws Exception {
    Configuration conf = new Configuration();
    conf.setLong("dfs.blockreport.intervalMsec", 1000);
    FileSystem fs = null;/* w ww  .j a v  a2  s.c  o  m*/
    DFSClient dfsClient = null;
    LocatedBlocks blocks = null;
    int replicaCount = 0;
    Random random = new Random();
    String outStr = null;

    MiniDFSCluster cluster = null;
    try {
        cluster = new MiniDFSCluster(conf, 3, true, null);
        cluster.waitActive();
        fs = cluster.getFileSystem();
        Path file1 = new Path("/testCorruptBlock");
        DFSTestUtil.createFile(fs, file1, 1024, (short) 3, 0);
        // Wait until file replication has completed
        DFSTestUtil.waitReplication(fs, file1, (short) 3);
        String block = DFSTestUtil.getFirstBlock(fs, file1).getBlockName();

        // Make sure filesystem is in healthy state
        outStr = runFsck(conf, 0, true, "/");
        System.out.println(outStr);
        assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));

        // corrupt replicas 
        File baseDir = new File(System.getProperty("test.build.data", "build/test/data"), "dfs/data");
        for (int i = 0; i < 6; i++) {
            File blockFile = new File(baseDir, "data" + (i + 1) + "/current/" + block);
            if (blockFile.exists()) {
                RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
                FileChannel channel = raFile.getChannel();
                String badString = "BADBAD";
                int rand = random.nextInt((int) channel.size() / 2);
                raFile.seek(rand);
                raFile.write(badString.getBytes());
                raFile.close();
            }
        }
        // Read the file to trigger reportBadBlocks
        try {
            IOUtils.copyBytes(fs.open(file1), new IOUtils.NullOutputStream(), conf, true);
        } catch (IOException ie) {
            // Ignore exception
        }

        dfsClient = new DFSClient(new InetSocketAddress("localhost", cluster.getNameNodePort()), conf);
        blocks = dfsClient.namenode.getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
        replicaCount = blocks.get(0).getLocations().length;
        while (replicaCount != 3) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ignore) {
            }
            blocks = dfsClient.namenode.getBlockLocations(file1.toString(), 0, Long.MAX_VALUE);
            replicaCount = blocks.get(0).getLocations().length;
        }
        assertTrue(blocks.get(0).isCorrupt());

        // Check if fsck reports the same
        outStr = runFsck(conf, 1, true, "/");
        System.out.println(outStr);
        assertTrue(outStr.contains(NamenodeFsck.CORRUPT_STATUS));
        assertTrue(outStr.contains("testCorruptBlock"));
    } finally {
        if (cluster != null) {
            cluster.shutdown();
        }
    }
}

From source file:com.intervigil.micdroid.MainActivity.java

@Override
public void onExport(Recording r) {
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Log.w(TAG, "onExport: External media is not available");
        Toast.makeText(mContext, R.string.recording_options_export_external_media_unavailable,
                Toast.LENGTH_SHORT).show();
        return;//from  w w w.  j a va  2 s. c  om
    }
    File externalMusicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
    if (!externalMusicDir.exists() && !externalMusicDir.mkdirs()) {
        Log.e(TAG, "onExport: Failed to create external music directory");
        Toast.makeText(mContext, R.string.recording_options_export_external_music_dir_unavailable,
                Toast.LENGTH_SHORT).show();
        return;
    }

    File exported = new File(externalMusicDir, r.getName());
    FileChannel srcChannel = null;
    FileChannel dstChannel = null;
    try {
        srcChannel = mContext.openFileInput(r.getName()).getChannel();
        dstChannel = new FileOutputStream(exported).getChannel();

        srcChannel.transferTo(0, srcChannel.size(), dstChannel);

        Toast.makeText(mContext, R.string.recording_options_export_complete, Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Log.e(TAG, "onExport: Failed to export file: " + r.getName());
        e.printStackTrace();
        Toast.makeText(mContext, R.string.recording_options_export_copy_error, Toast.LENGTH_SHORT).show();
    } finally {
        try {
            if (srcChannel != null) {
                srcChannel.close();
            }
            if (dstChannel != null) {
                dstChannel.close();
            }
        } catch (IOException e) {
            // Do nothing
        }
    }
}

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

public int checkPduResult() {
    if (!mPduFile.exists()) {
        Log.e(MmsApp.TXN_TAG, "checkPduResult MMS Fail, no pduFile = " + mPduFile);
        return SmsManager.MMS_ERROR_UNSPECIFIED;
    }/*from  www .j  a v a  2  s.c  om*/
    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;

        // 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.python.pydev.core.REF.java

/**
 * Copy a file from one place to another.
 * /*  ww  w .ja va 2  s . c  o  m*/
 * Example from: http://www.exampledepot.com/egs/java.nio/File2File.html
 * 
 * @param srcFilename the source file
 * @param dstFilename the destination
 */
public static void copyFile(String srcFilename, String dstFilename) {
    FileChannel srcChannel = null;
    FileChannel dstChannel = null;
    try {
        // Create channel on the source
        srcChannel = new FileInputStream(srcFilename).getChannel();

        // Create channel on the destination
        dstChannel = new FileOutputStream(dstFilename).getChannel();

        // Copy file contents from source to destination
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        // Close the channels
        if (srcChannel != null) {
            try {
                srcChannel.close();
            } catch (IOException e) {
                Log.log(e);
            }
        }
        if (dstChannel != null) {
            try {
                dstChannel.close();
            } catch (IOException e) {
                Log.log(e);
            }
        }
    }

}

From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java

/**
 * @param sourceFile//from  w  w  w  .  j  av a2  s. c om
 * @param destFile
 * @throws IOException Copy a file to some desired location
 */
@SuppressWarnings("resource")
public static void copyFile(File sourceFile, File destFile) throws IOException {
    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();

        // previous code: destination.transferFrom(source, 0, source.size());
        // to avoid infinite loops, should be:
        long count = 0;
        long size = source.size();
        while ((count += destination.transferFrom(source, count, size - count)) < size)
            ;
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:display.containers.FileManager.java

public static boolean copyFile(File from, File to) throws IOException {

    boolean created = to.createNewFile();

    if (created) {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {//from w  w  w. j  a  va  2 s . com
            fromChannel = new FileInputStream(from).getChannel();
            toChannel = new FileOutputStream(to).getChannel();

            toChannel.transferFrom(fromChannel, 0, fromChannel.size());

            // set the flags of the to the same as the from
            to.setReadable(from.canRead());
            to.setWritable(from.canWrite());
            to.setExecutable(from.canExecute());
        } finally {
            if (fromChannel != null) {
                fromChannel.close();
            }
            if (toChannel != null) {
                toChannel.close();
            }
            return false;
        }
    }
    return created;
}