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:br.com.manish.ahy.kernel.util.FileUtil.java

public static byte[] readFileAsBytes(String path) {

    byte[] fileArray = null;

    try {//w w w. ja  v a2 s . c  o  m
        File file = new File(path);
        if (file.length() > Integer.MAX_VALUE) {
            throw new OopsException("Oversized file :-( can't read it, sorry: " + path);
        }

        fileArray = new byte[(int) file.length()];
        DataInputStream dis;
        dis = new DataInputStream(new FileInputStream(file));
        dis.readFully(fileArray);
        dis.close();

    } catch (Exception e) {
        throw new OopsException(e, "Problems when reading: [" + path + "].");
    }

    return fileArray;
}

From source file:com.clustercontrol.jobmanagement.util.JobmapIconImageUtil.java

/**
 * ?//from  w  ww. j av a  2  s . c  om
 * @param filepath 
 * @throws Exception
 */
private static byte[] getFileData(String filepath) throws Exception {
    File file = new File(filepath);
    String filename = file.getName();
    int filesize = (int) file.length();
    if (filesize > MAX_FILESIZE) {
        m_log.warn("getFileData(), file size is too large");
        throw new Exception(Messages.getString("message.job.143"));
    }
    byte[] filedata = null;

    /*
     * 
     */
    FileInputStream stream = null;
    try {
        stream = new FileInputStream(filepath);
        filedata = new byte[filesize];
        int readsize = stream.read(filedata, 0, filesize);
        m_log.debug("UploadImage readsize = " + readsize + ", filesize = " + filesize);
        m_log.debug("path=" + filepath + ", name=" + filename);
    } catch (FileNotFoundException e) {
        m_log.warn("getFileData(), " + e.getMessage(), e);
        throw new Exception(Messages.getString("file.not.found"), e);
    } catch (Exception e) {
        m_log.warn("getFileData(), " + e.getMessage(), e);
        throw e;
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                m_log.warn("getFileData(), " + e.getMessage(), e);
            }
            stream = null;
        }
    }
    return filedata;
}

From source file:org.openmeetings.app.data.file.FileUtils.java

public static long getSize(File dir) {
    long size = 0;
    if (dir.isFile()) {
        size = dir.length();
    } else {// w  w w . ja  v a 2  s. c  o m
        File[] subFiles = dir.listFiles();

        for (File file : subFiles) {
            if (file.isFile()) {
                size += file.length();
            } else {
                size += getSize(file);
            }

        }
    }
    return size;
}

From source file:be.vds.jtbdive.core.utils.FileUtilities.java

public static void replaceAllInFile(File file, String[] oldValues, String[] newValues) throws IOException {
    byte[] b = new byte[(int) file.length()];
    FileInputStream is = new FileInputStream(file);
    is.read(b);/*from  w ww  .  j av a 2 s  .  co  m*/
    is.close();
    String s = new String(b);

    for (int i = 0; i < oldValues.length; i++) {
        s = s.replaceAll(oldValues[i], newValues[i]);
    }

    FileOutputStream os = new FileOutputStream(file);
    os.write(s.getBytes());
    os.flush();
    os.close();

}

From source file:net.bpelunit.util.FileUtil.java

public static byte[] readFile(File f) throws IOException {
    FileInputStream bprInputStream = null;
    try {//ww  w.j ava 2  s.  c om
        bprInputStream = new FileInputStream(f);
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream((int) f.length());
        IOUtils.copy(bprInputStream, bytesOut);

        return bytesOut.toByteArray();
    } finally {
        IOUtils.closeQuietly(bprInputStream);
    }
}

From source file:Main.java

/**
 * Determine whether a file is a ZIP File.
 *//*from   w w  w  .  j  a va2s . c  o m*/
public 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:Main.java

public static void compressFileIfNeeded(String filePath) {
    File f = new File(filePath);

    Bitmap bitmap;/*from  ww w.  java2 s  .  c  o m*/
    bitmap = BitmapFactory.decodeFile(filePath);
    int MAX_IMAGE_SIZE = 1000 * 1024;
    int streamLength = (int) f.length();
    if (streamLength > MAX_IMAGE_SIZE) {
        int compressQuality = 105;
        ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
        while (streamLength >= MAX_IMAGE_SIZE && compressQuality > 5) {
            try {
                bmpStream.flush();//to avoid out of memory error
                bmpStream.reset();
            } catch (IOException e) {
                e.printStackTrace();
            }
            compressQuality -= 5;
            bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
            byte[] bmpPicByteArray = bmpStream.toByteArray();
            streamLength = bmpPicByteArray.length;
            Log.d("test upload", "Quality: " + compressQuality);
            Log.d("test upload", "Size: " + streamLength);
        }

        FileOutputStream fo;

        try {
            f.delete();
            f = new File(filePath);
            fo = new FileOutputStream(f);
            fo.write(bmpStream.toByteArray());
            fo.flush();
            fo.close();
            ExifInterface exif = new ExifInterface(f.getAbsolutePath());
            exif.setAttribute(ExifInterface.TAG_ORIENTATION, "6");
            exif.saveAttributes();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:eg.nileu.cis.nilestore.main.HttpDealer.java

/**
 * Put./*www  . j  a va  2 s  . co  m*/
 * 
 * @param filepath
 *            the filepath
 * @param url
 *            the url
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void put(String filepath, String url) throws ClientProtocolException, IOException {
    url = url + (url.endsWith("/") ? "" : "/") + "upload?t=json";
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filepath);
    final double filesize = file.length();

    ContentBody fbody = new FileBodyProgress(file, new ProgressListener() {

        @Override
        public void transfered(long bytes, float rate) {
            int percent = (int) ((bytes / filesize) * 100);
            String bar = ProgressUtils.progressBar("Uploading file to the gateway : ", percent, rate);
            System.err.print("\r" + bar);
            if (percent == 100) {
                System.err.println();
                System.err.println("wait the gateway is processing and saving your file");
            }
        }
    });

    entity.addPart("File", fbody);

    post.setEntity(entity);

    HttpResponse response = client.execute(post);

    if (response != null) {
        System.err.println(response.getStatusLine());
        HttpEntity ht = response.getEntity();
        String json = EntityUtils.toString(ht);
        JSONParser parser = new JSONParser();
        try {
            JSONObject obj = (JSONObject) parser.parse(json);
            System.out.println(obj.get("cap"));
        } catch (ParseException e) {
            System.err.println("Error during parsing the response: " + e.getMessage());
            System.exit(-1);
        }
    } else {
        System.err.println("Error: response = null");
    }

    client.getConnectionManager().shutdown();
}

From source file:com.feilong.tools.net.ZClientTest.java

/**
 * Gets the files.//from  www  .j a va 2s  . c om
 * 
 * @param ftp
 *            the ftp
 * @param localDir
 *            the local dir
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private static void testGetFiles(FTPClient ftp, File localDir) throws IOException {
    String[] names = ftp.listNames();
    for (String name : names) {
        File file = new File(localDir.getPath() + File.separator + name);
        if (!file.exists()) {
            file.createNewFile();
        }
        long pos = file.length();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        raf.seek(pos);
        ftp.setRestartOffset(pos);
        InputStream is = ftp.retrieveFileStream(name);
        if (is == null) {
            log.info("no such file:" + name);
        } else {
            log.info("start getting file:" + name);
            int b;
            while ((b = is.read()) != -1) {
                raf.write(b);
            }
            is.close();
            if (ftp.completePendingCommand()) {
                log.info("done!");
            } else {
                log.info("can't get file:" + name);
            }
        }
        raf.close();
    }
}

From source file:IORoutines.java

public static boolean equalContent(File file, byte[] content) throws IOException {
    long length = file.length();
    if (length > Integer.MAX_VALUE) {
        throw new IOException("File '" + file + "' too big");
    }/* w  w  w . j ava 2s.  co  m*/
    InputStream in = new FileInputStream(file);
    try {
        byte[] fileContent = loadExact(in, (int) length);
        return java.util.Arrays.equals(content, fileContent);
    } finally {
        in.close();
    }
}