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.orange.ocara.model.export.docx.DocxWriterTest.java

/**
 * Determine whether a file is a ZIP File.
 */// w w  w .j av  a 2  s .c om
private static boolean isZipFile(File file) throws IOException {
    if (file.isDirectory()) {
        return false;
    }
    if (!file.canRead()) {
        throw new IOException("Cannot read file " + file.getAbsolutePath());
    }
    if (file.length() < 4) {
        return false;
    }
    DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
    int test = in.readInt();
    in.close();
    return test == 0x504b0304;
}

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

/**
 * create an image item/*from w ww .  jav  a  2s. c  o m*/
 * 
 * @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 createImageItem(final String contentType, final File imageFile) {
    final FileItem imageItem = new DiskFileItem(ProtocolConstants.Parameters.Create.IMAGE_ITEM, contentType,
            false, imageFile.getName(), (int) imageFile.length(), DISK_FILE_REPOSITORY);

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

    return imageItem;
}

From source file:biospectra.BioSpectra.java

private static void utils(String[] args) throws Exception {
    String operation = args[1];//from  w w  w.java2s.  c  o m

    if (operation.equalsIgnoreCase("index")) {
        String indexDir = args[2];

        IndexUtil indexutil = new IndexUtil(indexDir);
        System.out.println("total docs : " + indexutil.countDocs());
        indexutil.close();
    } else if (operation.equalsIgnoreCase("fasta")) {
        String fastaDir = args[2];

        int count = 0;
        long size_sum = 0;
        List<File> fastaDocs = FastaFileHelper.findFastaDocs(fastaDir);
        for (File fastaDoc : fastaDocs) {
            System.out.println("found FASTA file : " + fastaDoc.getAbsolutePath());
            System.out.println("size> " + fastaDoc.length());
            count++;
            size_sum += fastaDoc.length();
        }
        System.out.println("SUMMARY");
        System.out.println("Count : " + count);
        System.out.println("Size in total : " + size_sum);
    } else if (operation.equalsIgnoreCase("nfasta")) {
        String fastaDir = args[2];

        int count = 0;
        long size_sum = 0;
        List<File> fastaDocs = FastaFileHelper.findNonFastaDocs(fastaDir);
        for (File fastaDoc : fastaDocs) {
            System.out.println("found non-FASTA file : " + fastaDoc.getAbsolutePath());
            System.out.println("size> " + fastaDoc.length());
            count++;
            size_sum += fastaDoc.length();
        }
        System.out.println("SUMMARY");
        System.out.println("Count : " + count);
        System.out.println("Size in total : " + size_sum);
    } else if (operation.equalsIgnoreCase("taxid")) {
        String dbDir = args[2];
        int taxid = Integer.parseInt(args[3]);

        TaxonDB db = new TaxonDB(dbDir);
        List<Taxonomy> taxon = db.getFullTaxonomyHierarchyByTaxid(taxid);
        for (Taxonomy t : taxon) {
            System.out.println(t.toString());
        }
        db.close();
    } else if (operation.equalsIgnoreCase("gi")) {
        String dbFile = args[2];
        int gi = Integer.parseInt(args[3]);

        TaxonDB db = new TaxonDB(dbFile);
        List<Taxonomy> taxon = db.getFullTaxonomyHierarchyByGI(gi);
        for (Taxonomy t : taxon) {
            System.out.println(t.toString());
        }
        db.close();
    }
}

From source file:io.kubernetes.client.util.SSLUtils.java

private static boolean loadDefaultStoreFile(KeyStore keyStore, File fileToLoad, char[] passphrase)
        throws CertificateException, NoSuchAlgorithmException, IOException {
    if (fileToLoad.exists() && fileToLoad.isFile() && fileToLoad.length() > 0) {
        keyStore.load(new FileInputStream(fileToLoad), passphrase);
        return true;
    }/* w w w . jav  a  2 s. co m*/
    return false;
}

From source file:com.flurry.proguard.UploadProGuardMapping.java

/**
 * Get the payload for creating the Upload in the metadata service
 *
 * @param zippedFile the archive to upload
 * @param projectId the project's ID//  w ww.  ja  v  a2  s .c  o m
 * @return a JSON string to be sent to the metadata service
 */
private static String getUploadJson(File zippedFile, String projectId) {
    return getUploadTemplate().replace("UPLOAD_SIZE", Long.toString(zippedFile.length())).replace("PROJECT_ID",
            projectId);
}

From source file:com.wodify.cordova.plugin.filepicker.FilePicker.java

/**
 * Returns file in byte array./*from w  ww.ja v a 2 s .c om*/
 * See: https://gist.github.com/utkarsh2012/1276960
 * @param  file        File to convert to byte array.
 */
private static byte[] loadFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    long length = file.length();

    if (length > Integer.MAX_VALUE) {
        return null;
    }

    byte[] bytes = new byte[(int) length];

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

    if (offset < bytes.length) {
        throw new IOException("Could not completely read file " + file.getName());
    }

    is.close();
    return bytes;
}

From source file:com.dahl.brendan.wordsearch.view.IOService.java

private static void readFile(Context context, File file, boolean overwrite) {
    if (file.canRead()) {
        if (overwrite) {
            context.getContentResolver().delete(Word.CONTENT_URI, "1", null);
        }/*from   w w w.j a va  2s. com*/
        try {
            byte[] buffer = new byte[(int) file.length()];
            BufferedInputStream f = new BufferedInputStream(new FileInputStream(file));
            f.read(buffer);
            JSONArray array = new JSONArray(new String(buffer));
            List<ContentValues> values = new LinkedList<ContentValues>();
            for (int i = 0; i < array.length(); i++) {
                Log.v(LOGTAG, array.getString(i));
                ContentValues value = new ContentValues();
                value.put(Word.WORD, array.getString(i));
                values.add(value);
            }
            context.getContentResolver().bulkInsert(Word.CONTENT_URI, values.toArray(new ContentValues[0]));
        } catch (IOException e) {
            Log.e(LOGTAG, "IO error", e);
        } catch (JSONException e) {
            Log.e(LOGTAG, "bad input", e);
        }
    }
}

From source file:com.dv.Utils.Tools.java

/**
 * install app//  ww w  .ja v a  2  s .co  m
 *
 * @param context
 * @param filePath
 * @return whether apk exist
 */
public static boolean install(Context context, String filePath) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    File file = new File(filePath);

    if ((file != null) && (file.length() > 0) && file.exists() && file.isFile()) {
        i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);

        return true;
    }

    return false;
}

From source file:fm.last.commons.test.LastAssertions.java

/**
 * Asserts that the *contents* of the passed files are equal.
 * //from ww w.ja v a  2 s . c o  m
 * @param message Failure message.
 * @param expectedFile File containing expected data.
 * @param expectedFileEncoding Encoding of expected file.
 * @param actualFile File to compare.
 * @param actualFileEncoding Encoding of actual file.
 * @throws IOException If an error occurs comparing the file contents.
 */
public static void assertFileEquals(String message, File expectedFile, Charset expectedFileEncoding,
        File actualFile, Charset actualFileEncoding) throws IOException {
    boolean equal = true;

    long expectedFileLength = expectedFile.length();
    long actualFileLength = actualFile.length();
    if (expectedFileLength != actualFileLength) {
        equal = false;
    } else {
        equal = fileBytesEqual(expectedFile, actualFile);
    }
    if (!equal) {

        if (message == null) {
            message = "";
        }
        if (Math.max(expectedFileLength, actualFileLength) < JedecByteUnit.MEGABYTES.toBytes(1)) {
            expectedFileEncoding = resolveToDefault(expectedFileEncoding);
            actualFileEncoding = resolveToDefault(actualFileEncoding);
            throw new ComparisonFailure(message, FileUtils.readFileToString(expectedFile, expectedFileEncoding),
                    FileUtils.readFileToString(actualFile, actualFileEncoding));
        } else {
            Assert.fail(expectedFile + " not equal to " + actualFile);
        }

    }
}

From source file:com.flexive.shared.media.FxMediaEngine.java

/**
 * Identify a file, returning metadata/*from   w  ww.  j av a2 s. c o m*/
 *
 * @param mimeType if not null it will be used to call the correct identify routine
 * @param file     the file to identify
 * @return metadata
 */
public static FxMetadata identify(String mimeType, File file) {
    if (mimeType == null) {
        byte[] header = new byte[5];
        //read the first 5 bytes
        if (file.length() > 5) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                if (fis.read(header, 0, 5) != 5)
                    header = null;
            } catch (IOException e) {
                LOG.error(e);
            } finally {
                try {
                    if (fis != null)
                        fis.close();
                } catch (IOException e) {
                    LOG.error(e);
                }
            }
        }
        mimeType = detectMimeType(header, file.getName());
    }
    // image file identification
    if (mimeType.startsWith("image")) {
        try {
            //try native first
            return FxMediaNativeEngine.identify(mimeType, file);
        } catch (FxApplicationException e) {
            if (FxMediaImageMagickEngine.IM_IDENTIFY_POSSIBLE) {
                try {
                    return FxMediaImageMagickEngine.identify(mimeType, file);
                } catch (FxApplicationException e1) {
                    LOG.error(e1);
                }
            } else
                LOG.error(e);
        }
    } else if (mimeType.startsWith("audio")) {
        // audio file identification (optional) - TODO: do the same for documents
        // or make this really extensible
        final FxMetadata meta = invokeIdentify(mimeType, file, CLS_AUDIO_EXTRACTOR);
        if (meta != null) {
            return meta;
        }
        // video file identification
    } else if (mimeType.startsWith("video")) {
        // video file identification (optional) - TODO: do the same for documents
        // or make this really extensible
        final FxMetadata meta = invokeIdentify(mimeType, file, CLS_VIDEO_EXTRACTOR);
        if (meta != null) {
            return meta;
        }
    }
    //last resort: unknown
    return new FxUnknownMetadataImpl(mimeType, file.getName());
}