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:net.firejack.platform.core.utils.SecurityHelper.java

public static byte[] read64(String name) throws IOException {
    File file = new File(name);
    FileInputStream stream = new FileInputStream(file);
    byte[] bytes = new byte[(int) file.length()];
    stream.read(bytes);//from   w w  w  .  java2 s  . c  o m
    stream.close();
    return Base64.decode(bytes);
}

From source file:Main.java

public static ByteBuffer mapFile(File f, long offset, ByteOrder byteOrder) throws IOException {
    FileInputStream dataFile = new FileInputStream(f);
    try {/*ww w.  j  a  v a  2s  . c o m*/
        FileChannel fc = dataFile.getChannel();
        MappedByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, offset, f.length() - offset);
        buffer.order(byteOrder);
        return buffer;
    } finally {
        dataFile.close(); // this *also* closes the associated channel, fc
    }
}

From source file:info.servertools.core.util.FileUtils.java

/**
 * Check the size of a directory//from w ww.  ja  v a  2s  . com
 *
 * @param directory
 *         the directory to check
 *
 * @return the size of the directory in bytes
 */
public static long getFolderSize(File directory) {

    long length = 0;
    if (directory.exists() && directory.isDirectory()) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile())
                    length += file.length();
                else
                    length += getFolderSize(file);
            }
        }
    }

    return length;
}

From source file:Main.java

public static byte[] readFromFile(String fileName, int offset, int len) {
    if (fileName == null) {
        return null;
    }//from   w w  w. ja v  a 2s .  c o m

    File file = new File(fileName);
    if (!file.exists()) {
        //WLog.i(FileUtils.class, "readFromFile: file not found");
        return null;
    }

    if (len == -1) {
        len = (int) file.length();
    }

    if (offset < 0) {
        //WLog.e(FileUtils.class, "readFromFile invalid offset:" + offset);
        return null;
    }
    if (len <= 0) {
        //WLog.e(FileUtils.class, "readFromFile invalid len:" + len);
        return null;
    }
    if (offset + len > (int) file.length()) {
        //WLog.e(FileUtils.class, "readFromFile invalid file len:" + file.length());
        return null;
    }

    byte[] b = null;
    try {
        RandomAccessFile in = new RandomAccessFile(fileName, "r");
        b = new byte[len];
        in.seek(offset);
        in.readFully(b);
        in.close();

    } catch (Exception e) {
        // WLog.e(FileUtils.class, "readFromFile : errMsg = " + e.getMessage());
        e.printStackTrace();
    }
    return b;
}

From source file:Main.java

/**
 * Read a text file into a String, optionally limiting the length.
 * /*from  ww  w. j a  v  a 2 s. c o m*/
 * @param file
 *            to read (will not seek, so things like /proc files are OK)
 * @param max
 *            length (positive for head, negative of tail, 0 for no limit)
 * @param ellipsis
 *            to add of the file was truncated (can be null)
 * @return the contents of the file, possibly truncated
 * @throws IOException
 *             if something goes wrong reading the file
 */
public static String readTextFile(File file, int max, String ellipsis) throws IOException {
    InputStream input = new FileInputStream(file);
    try {
        long size = file.length();
        if (max > 0 || (size > 0 && max == 0)) { // "head" mode: read the
                                                 // first N bytes
            if (size > 0 && (max == 0 || size < max))
                max = (int) size;
            byte[] data = new byte[max + 1];
            int length = input.read(data);
            if (length <= 0)
                return "";
            if (length <= max)
                return new String(data, 0, length);
            if (ellipsis == null)
                return new String(data, 0, max);
            return new String(data, 0, max) + ellipsis;
        } else if (max < 0) { // "tail" mode: keep the last N
            int len;
            boolean rolled = false;
            byte[] last = null, data = null;
            do {
                if (last != null)
                    rolled = true;
                byte[] tmp = last;
                last = data;
                data = tmp;
                if (data == null)
                    data = new byte[-max];
                len = input.read(data);
            } while (len == data.length);

            if (last == null && len <= 0)
                return "";
            if (last == null)
                return new String(data, 0, len);
            if (len > 0) {
                rolled = true;
                System.arraycopy(last, len, last, 0, last.length - len);
                System.arraycopy(data, 0, last, last.length - len, len);
            }
            if (ellipsis == null || !rolled)
                return new String(last);
            return ellipsis + new String(last);
        } else { // "cat" mode: size unknown, read it all in streaming
                 // fashion
            ByteArrayOutputStream contents = new ByteArrayOutputStream();
            int len;
            byte[] data = new byte[1024];
            do {
                len = input.read(data);
                if (len > 0)
                    contents.write(data, 0, len);
            } while (len == data.length);
            return contents.toString();
        }
    } finally {
        input.close();
    }
}

From source file:MakeDirectories.java

private static void fileData(File f) {
    System.out.println("Absolute path: " + f.getAbsolutePath() + "\n Can read: " + f.canRead()
            + "\n Can write: " + f.canWrite() + "\n getName: " + f.getName() + "\n getParent: " + f.getParent()
            + "\n getPath: " + f.getPath() + "\n length: " + f.length() + "\n lastModified: "
            + f.lastModified());/*from ww w.j  a  v  a2 s  .c o m*/
    if (f.isFile())
        System.out.println("It's a file");
    else if (f.isDirectory())
        System.out.println("It's a directory");
}

From source file:com.radadev.xkcd.Comics.java

public static void downloadComic(Integer comicNumber, Context context)
        throws FileNotFoundException, IOException {
    ComicDbAdapter dbAdapter = new ComicDbAdapter(context);
    dbAdapter.open();/*w  w  w  .  j ava 2 s.co  m*/
    try {
        dbAdapter.updateComic(comicNumber);
        File file = new File(getSdDir(context), comicNumber.toString() + ".png");
        if (file.length() <= 0) {
            Cursor cursor = dbAdapter.fetchComic(comicNumber);
            String url = cursor.getString(cursor.getColumnIndexOrThrow(Comics.SQL_KEY_IMAGE));

            if (url == null || url.length() == 0) {
                dbAdapter.updateComic(comicNumber);
                cursor.close();
                cursor = dbAdapter.fetchComic(comicNumber);
                url = cursor.getString(cursor.getColumnIndexOrThrow(Comics.SQL_KEY_IMAGE));
            }
            cursor.close();

            Bitmap bitmap = Comics.downloadBitmap(url);
            FileOutputStream fileStream = new FileOutputStream(file);
            bitmap.compress(CompressFormat.PNG, 100, fileStream);
            bitmap.recycle();
            fileStream.close();
        }
    } finally {
        dbAdapter.close();
    }
}

From source file:com.shmsoft.dmass.services.Util.java

public static byte[] getBytesFromFile(File file) throws IOException {
    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 RuntimeException(file.getName() + " is too large");
    }/*from   w  w  w . ja v  a  2 s. c  om*/

    // 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:Main.java

static String readStringFromFile(File theFile) {
    String myReturnString;/*from ww  w.  j a va 2 s  .co  m*/
    if (theFile == null) {
        myReturnString = "No File was opened";
    } else {
        try {
            FileInputStream in = new FileInputStream(theFile);
            int size = (int) theFile.length();
            byte[] data = new byte[size];
            /* let's read in the file (which may not all arrive in one chomp...)*/;
            int bytes_read = 0;
            while (bytes_read < size) {
                bytes_read += in.read(data, bytes_read, size - bytes_read);
            }
            ;
            myReturnString = new String(data); // used to be new String( data, 0 );
        } catch (Exception exc) {
            myReturnString = "Error opening file:" + exc;
        }
        ;
    }
    ;
    return myReturnString;
}

From source file:it.geosolutions.geostore.services.rest.auditing.AuditingTestsUtils.java

static String readFile(File file) {
    try {/*from   ww  w.  java2  s . c  o m*/
        FileInputStream input = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];
        input.read(data);
        input.close();
        return new String(data);
    } catch (Exception exception) {
        throw new AuditingException(exception, "Error reading file '%s' content.", file.getAbsolutePath());
    }
}