Example usage for java.io File length

List of usage examples for java.io File length

Introduction

In this page you can find the example usage for java.io File length.

Prototype

public long length() 

Source Link

Document

Returns the length of the file denoted by this abstract pathname.

Usage

From source file:com.alibaba.otter.shared.common.utils.NioUtilsPerformance.java

public static void mappedTest(File source, File target) throws Exception {
    FileInputStream fis = null;//from   ww  w  . j a v a 2  s  . c o  m
    FileOutputStream fos = null;
    MappedByteBuffer mapbuffer = null;

    try {
        long fileSize = source.length();
        final byte[] outputData = new byte[(int) fileSize];
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);
        FileChannel sChannel = fis.getChannel();

        target.createNewFile();

        mapbuffer = sChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);
        for (int i = 0; i < fileSize; i++) {
            outputData[i] = mapbuffer.get();
        }

        mapbuffer.clear();
        fos.write(outputData);
        fos.flush();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);

        if (mapbuffer == null) {
            return;
        }

        final Object buffer = mapbuffer;

        AccessController.doPrivileged(new PrivilegedAction() {

            public Object run() {
                try {
                    Method clean = buffer.getClass().getMethod("cleaner", new Class[0]);

                    if (clean == null) {
                        return null;
                    }
                    clean.setAccessible(true);
                    sun.misc.Cleaner cleaner = (sun.misc.Cleaner) clean.invoke(buffer, new Object[0]);
                    cleaner.clean();
                } catch (Throwable ex) {
                }

                return null;
            }
        });
    }
}

From source file:mobile.service.core.ClientLogService.java

/**
 * /*from   ww w. jav a  2s.co  m*/
 * 
 * @param from ??,
 * @param sourceFile length>0
 * @param description ??,?
 */
public static void uploadLog(final String from, File sourceFile, final String description) {
    if (sourceFile == null || StringUtils.isBlank(from)) {
        throw new IllegalArgumentException("illegal param. sourceFile = " + sourceFile + ", from = " + from);
    }
    if (sourceFile.length() <= 0) {
        throw new IllegalArgumentException("sourceFile.length() <= 0");
    }

    String absDestFilePath = JPAUtil.indieTransaction(new IndieTransactionFunc<String>() {

        @Override
        public String call(EntityManager em) {
            // ?
            DateTime now = new DateTime();
            MobileClientLog log = new MobileClientLog();
            log.setCreateTime(now.toDate());
            log.setDescription(description);
            log.setDevice(from);
            JPA.em().persist(log);

            String destFileName = now.toString("yyyyMMdd-HHmmss") + "-" + log.getId() + ".log";
            String absDestFilePath = FileService.getMobileAbsUploadPath() + "clientLog/" + destFileName;
            String relDestFilePath = FileService.getMobileRelUploadPath() + "clientLog/" + destFileName;

            log.setLogFileUrl(relDestFilePath);
            JPA.em().merge(log);

            return absDestFilePath;
        }
    });

    File destFile = new File(absDestFilePath);
    if (!destFile.getParentFile().exists()) {
        destFile.getParentFile().mkdirs();
    }
    FileService.copyFile(sourceFile.getAbsolutePath(), absDestFilePath);
}

From source file:net.dv8tion.jda.core.utils.IOUtil.java

/**
 * Used as an alternate to Java's nio Files.readAllBytes.
 * <p>/*from   w w w  .  ja va  2s.  co m*/
 * This customized version for File is provide (instead of just using {@link #readFully(java.io.InputStream)} with a FileInputStream)
 * because
 * with a File we can determine the total size of the array and do not need to have a buffer. This results
 * in a memory footprint that is half the size of {@link #readFully(java.io.InputStream)}
 * <p>
 * Code provided from <a href="http://stackoverflow.com/a/6276139">http://stackoverflow.com/a/6276139</a>
 *
 * @param file
 *          The file from which we should retrieve the bytes from
 * @return
 *      A byte[] containing all of the file's data
 * @throws IOException
 *      Thrown if there is a problem while reading the file.
 */
public static byte[] readFully(File file) throws IOException {
    Args.notNull(file, "File");
    Args.check(file.exists(), "Provided file does not exist!");

    try (InputStream is = new FileInputStream(file)) {
        // Get the size of the file
        long length = file.length();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            throw new IOException("Cannot read the file into memory completely due to it being too large!");
            // File is too large
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }

        // Close the input stream and return bytes
        is.close();
        return bytes;
    }
}

From source file:io.druid.data.input.impl.prefetch.Fetcher.java

private static Closeable getFileCloser(final File file, final AtomicLong fetchedBytes) {
    return () -> {
        final long fileSize = file.length();
        file.delete();/*from   w  w w .j  av a 2 s  . c o m*/
        fetchedBytes.addAndGet(-fileSize);
    };
}

From source file:TripleDES.java

/** Read a TripleDES secret key from the specified file */
public static SecretKey readKey(File f)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    // Read the raw bytes from the keyfile
    DataInputStream in = new DataInputStream(new FileInputStream(f));
    byte[] rawkey = new byte[(int) f.length()];
    in.readFully(rawkey);/* w w  w  .j av  a  2 s .c o  m*/
    in.close();

    // Convert the raw bytes to a secret key like this
    DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
    SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
    SecretKey key = keyfactory.generateSecret(keyspec);
    return key;
}

From source file:in.goahead.apps.util.URLUtils.java

public static void DownloadStream(InputStream inputStream, String outputFile, long skipLength)
        throws IOException {
    File outputFileObj = new File(outputFile);
    boolean appendStreamData = false;
    if (skipLength > 0) {
        appendStreamData = true;/*  w  ww .j a v  a 2  s  .c o m*/
        skipLength = outputFileObj.length();
    }
    OutputStream outputStream = new FileOutputStream(outputFile, appendStreamData);
    //   if(inputStream.skip(skipLength) == skipLength) {
    DownloadStream(inputStream, outputStream);
    //   }
    outputStream.flush();
    outputStream.close();
}

From source file:Main.java

private static byte[] readFileToBuffer(String filePath) {
    File inFile = new File(filePath);
    if (!inFile.exists()) {
        Log.d(TAG, "<readFileToBuffer> " + filePath + " not exists!!!");
        return null;
    }/* w w  w  .j ava  2  s .  c  o  m*/

    RandomAccessFile rafIn = null;
    try {
        rafIn = new RandomAccessFile(inFile, "r");
        int len = (int) inFile.length();
        byte[] buffer = new byte[len];
        rafIn.read(buffer);
        return buffer;
    } catch (IOException e) {
        Log.e(TAG, "<readFileToBuffer> Exception ", e);
        return null;
    } finally {
        try {
            if (rafIn != null) {
                rafIn.close();
                rafIn = null;
            }
        } catch (IOException e) {
            Log.e(TAG, "<readFileToBuffer> close IOException ", e);
        }
    }
}

From source file:de.ingrid.portal.global.UtilsFileHelper.java

/**
 * Write String into file/*from   ww w.  ja v  a 2s .c  o  m*/
 * 
 * @param path
 * @param content
 * @throws IOException
 */
public static void writeContentIntoFile(String path, String content) throws IOException {
    if (path != null) {
        File file = new File(path);
        if (file.length() < 1) {
            if (content != null) {
                Writer writer = null;
                writer = new FileWriter(path);
                writer.write(content);
                writer.close();
            } else {
                if (log.isErrorEnabled()) {
                    log.error("Content is null!");
                }
            }
        }
    }
}

From source file:de.metalcon.musicStorageServer.protocol.CreateRequestTest.java

/**
 * create a music item//from   ww w. j  a  v  a2  s . com
 * 
 * @param contentType
 *            content type of the music file
 * @param musicFile
 *            file handle to the music file
 * @return music item representing the music file passed
 */
private static FileItem createMusicItem(final String contentType, final File musicFile) {
    final FileItem musicItem = new DiskFileItem(ProtocolConstants.Parameter.Create.MUSIC_ITEM, contentType,
            false, musicFile.getName(), (int) musicFile.length(), DISK_FILE_REPOSITORY);

    // reason for call of getOutputStream: bug in commons.IO
    // called anyway to create file
    try {
        final OutputStream outputStream = musicItem.getOutputStream();
        final InputStream inputStream = new FileInputStream(musicFile);
        IOUtils.copy(inputStream, outputStream);
    } catch (final IOException e) {
        e.printStackTrace();
        fail("music item creation failed!");
    }

    return musicItem;
}

From source file:Main.java

public static String mergeFlockedFiles(String FilePath) {

    String result = null;/* ww w  .  j  av a  2  s .c  om*/
    try {
        result = java.net.URLDecoder.decode(FilePath, "UTF-8");
    } catch (UnsupportedEncodingException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    String fileName = result.substring(result.lastIndexOf('/') + 1);
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

        File flockedFilesFolder = new File(
                Environment.getExternalStorageDirectory() + File.separator + "FlockLoad");
        System.out.println("FlockedFileDir: " + flockedFilesFolder);
        long leninfile = 0, leng = 0;
        int count = 1, data = 0;
        int bytesRead = 0;
        try {
            File filename = new File(flockedFilesFolder.toString() + "/" + fileName);
            if (filename.exists())
                filename.delete();
            //BUFFER_SIZE = (int) filename.length();
            System.out.println("filename: " + filename);
            FileOutputStream fos = new FileOutputStream(filename, true);

            while (true) {
                File filepart = new File(filename + ".part" + count);
                System.out.println("part filename: " + filepart);
                if (filepart.exists()) {
                    FileInputStream fis = new FileInputStream(filepart);
                    byte fileBytes[] = new byte[(int) filepart.length()];
                    bytesRead = fis.read(fileBytes, 0, (int) filepart.length());
                    assert (bytesRead == fileBytes.length);
                    assert (bytesRead == (int) filepart.length());
                    fos.write(fileBytes);
                    fos.flush();
                    fileBytes = null;
                    fis.close();
                    fis = null;
                    count++;
                    filepart.delete();
                } else
                    break;
            }
            fos.close();
            fos = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return fileName;
}