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:com.jerrellmardis.amphitheatre.util.Utils.java

public static void backupDatabase(Context ctx) {
    try {// ww  w.j a v a  2s .  c om
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//" + ctx.getApplicationContext().getPackageName()
                    + "//databases//amphitheatre.db";
            String backupDBPath = "amphitheatre.db";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
            }
        }
    } catch (Exception e) {
        Log.i(Utils.class.getSimpleName(), "Unable to backup database");
    }
}

From source file:com.todotxt.todotxttouch.util.Util.java

public static void copyFile(File origFile, File newFile, boolean overwrite) {
    if (!origFile.exists()) {
        Log.e(TAG, "Error renaming file: " + origFile + " does not exist");

        throw new TodoException("Error copying file: " + origFile + " does not exist");
    }/* w w w.j a va 2s . c  o m*/

    createParentDirectory(newFile);

    if (!overwrite && newFile.exists()) {
        Log.e(TAG, "Error copying file: destination exists: " + newFile);

        throw new TodoException("Error copying file: destination exists: " + newFile);
    }

    try {
        FileInputStream fis = new FileInputStream(origFile);
        FileOutputStream fos = new FileOutputStream(newFile);
        FileChannel in = fis.getChannel();
        fos.getChannel().transferFrom(in, 0, in.size());
        fis.close();
        fos.close();
    } catch (Exception e) {
        Log.e(TAG, "Error copying " + origFile + " to " + newFile);

        throw new TodoException("Error copying " + origFile + " to " + newFile, e);
    }
}

From source file:org.nuclos.common2.IOUtils.java

/**
 * @param fileIn/*from   ww w . j a v a  2 s  .c o m*/
 * @param fileOut
 * @throws IOException
 */
public static void copyFile(File fileIn, File fileOut) throws IOException {
    FileChannel sourceChannel = null;
    FileChannel destinationChannel = null;
    try {
        sourceChannel = new FileInputStream(fileIn).getChannel();
        destinationChannel = new FileOutputStream(fileOut).getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
    } finally {
        try {
            if (sourceChannel != null) {
                sourceChannel.close();
            }
        } finally {
            if (destinationChannel != null) {
                destinationChannel.close();
            }
        }
    }
}

From source file:gridool.util.xfer.TransferUtils.java

public static void sendfile(@Nonnull final File file, final long fromPos, final long count,
        @Nullable final String writeDirPath, @Nonnull final InetAddress dstAddr, final int dstPort,
        final boolean append, final boolean sync, @Nonnull final TransferClientHandler handler)
        throws IOException {
    if (!file.exists()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist");
    }/* w  w w  . j ava 2 s. co  m*/
    if (!file.isFile()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " is not file");
    }
    if (!file.canRead()) {
        throw new IllegalArgumentException(file.getAbsolutePath() + " cannot read");
    }

    final SocketAddress dstSockAddr = new InetSocketAddress(dstAddr, dstPort);
    SocketChannel channel = null;
    Socket socket = null;
    final OutputStream out;
    try {
        channel = SocketChannel.open();
        socket = channel.socket();
        socket.connect(dstSockAddr);
        out = socket.getOutputStream();
    } catch (IOException e) {
        LOG.error("failed to connect: " + dstSockAddr, e);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
        throw e;
    }

    DataInputStream din = null;
    if (sync) {
        InputStream in = socket.getInputStream();
        din = new DataInputStream(in);
    }
    final DataOutputStream dos = new DataOutputStream(out);
    final StopWatch sw = new StopWatch();
    FileInputStream src = null;
    final long nbytes;
    try {
        src = new FileInputStream(file);
        FileChannel fc = src.getChannel();

        String fileName = file.getName();
        IOUtils.writeString(fileName, dos);
        IOUtils.writeString(writeDirPath, dos);
        long xferBytes = (count == -1L) ? fc.size() : count;
        dos.writeLong(xferBytes);
        dos.writeBoolean(append); // append=false
        dos.writeBoolean(sync);
        if (handler == null) {
            dos.writeBoolean(false);
        } else {
            dos.writeBoolean(true);
            handler.writeAdditionalHeader(dos);
        }

        // send file using zero-copy send
        nbytes = fc.transferTo(fromPos, xferBytes, channel);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sent a file '" + file.getAbsolutePath() + "' of " + nbytes + " bytes to "
                    + dstSockAddr.toString() + " in " + sw.toString());
        }

        if (sync) {// receive ack in sync mode
            long remoteRecieved = din.readLong();
            if (remoteRecieved != xferBytes) {
                throw new IllegalStateException(
                        "Sent " + xferBytes + " bytes, but remote node received " + remoteRecieved + " bytes");
            }
        }

    } catch (FileNotFoundException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw e;
    } finally {
        IOUtils.closeQuietly(src);
        IOUtils.closeQuietly(din, dos);
        IOUtils.closeQuietly(channel);
        NetUtils.closeQuietly(socket);
    }
}

From source file:Main.java

public static void copyFiles(String sourcePath, String targetPath) throws IOException {
    File srcDir = new File(sourcePath);
    File[] files = srcDir.listFiles();
    FileChannel in = null;
    FileChannel out = null;//from  w ww .  j  ava  2 s.  c om
    for (File file : files) {
        try {
            in = new FileInputStream(file).getChannel();
            File outDir = new File(targetPath);
            if (!outDir.exists()) {
                outDir.mkdirs();
            }
            File outFile = new File(targetPath + File.separator + file.getName());
            out = new FileOutputStream(outFile).getChannel();
            in.transferTo(0, in.size(), out);
        } finally {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        }
    }
}

From source file:com.nridge.core.base.std.FilUtl.java

/**
 * Copies an input file to the output file.  In an effort to promote
 * better performance, I/O channels are used for the operations.
 *
 * @param anInFile Represents the source file.
 * @param anOutFile Represents the destination file.
 * @throws IOException Related to stream building and read/write operations.
 *//*ww w .  j  a  v a  2s  .  c  o  m*/
static public void copy(File anInFile, File anOutFile) throws IOException

{
    FileChannel srcChannel, dstChannel;

    srcChannel = new FileInputStream(anInFile).getChannel();
    dstChannel = new FileOutputStream(anOutFile).getChannel();

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

From source file:org.apache.hadoop.dfs.TestDatanodeBlockScanner.java

public static boolean corruptReplica(String blockName, int replica) throws IOException {
    Random random = new Random();
    File baseDir = new File(System.getProperty("test.build.data"), "dfs/data");
    boolean corrupted = false;
    for (int i = replica * 2; i < replica * 2 + 2; i++) {
        File blockFile = new File(baseDir, "data" + (i + 1) + "/current/" + blockName);
        if (blockFile.exists()) {
            // Corrupt replica by writing random bytes into replica
            RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw");
            FileChannel channel = raFile.getChannel();
            String badString = "BADBAD";
            int rand = random.nextInt((int) channel.size() / 2);
            raFile.seek(rand);//from   w w  w .j  a  va  2  s. co  m
            raFile.write(badString.getBytes());
            raFile.close();
            corrupted = true;
        }
    }
    return corrupted;
}

From source file:de.wikilab.android.friendica01.Max.java

public static String readFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try {//  ww  w  .  j a  v  a 2  s . 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.defaultCharset().decode(bb).toString();
    } finally {
        stream.close();
    }
}

From source file:org.apache.pig.pigunit.PigTest.java

private static String readFile(File file) throws IOException {
    FileInputStream stream = new FileInputStream(file);
    try {// w w w  .  j  a  v  a 2s  .com
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        return Charset.defaultCharset().decode(bb).toString();
    } finally {
        stream.close();
    }
}

From source file:com.becapps.easydownloader.utils.Utils.java

@SuppressWarnings("resource")
public static void copyFile(File src, File dst) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    //if (!dst.exists()) {
    try {//from   w ww. j a  va2  s.c om
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
    /*} else {
       logger("w", "copyFile: destination already exists", DEBUG_TAG);
    }*/
}