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:importer.filters.CceFilter.java

static String readFile(String name) {
    try {//from   ww w .jav a  2 s .c o m
        File f = new File(name);
        FileInputStream fis = new FileInputStream(f);
        byte[] data = new byte[(int) f.length()];
        fis.read(data);
        return new String(data, "UTF-8");
    } catch (Exception e) {
        return "";
    }
}

From source file:com.aurel.track.exchange.docx.exporter.ImageUtil.java

/**
 * Add the image to docx//from   www.ja  va 2 s  .  c  o m
 * @param wordMLPackage
 * @param realNameWithPath
 * @param originalFilename
 * @param attachmentID
 * @param id
 * @param locale
 * @throws Exception
 */
private static void addImage(WordprocessingMLPackage wordMLPackage, String realNameWithPath,
        String originalFilename, String description, Integer attachmentID, String captionStyleId, int id,
        Locale locale) throws Exception {
    File file = new File(realNameWithPath);
    // Our utility method wants that as a byte array
    java.io.InputStream is = new java.io.FileInputStream(file);
    long length = file.length();
    // You cannot create an array using a long type.
    // It needs to be an int type.
    if (length > Integer.MAX_VALUE) {
        LOGGER.warn("File " + originalFilename + " too large and will not be added");
    } else {
        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;
        }
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            System.out.println("Could not completely read file " + file.getName());
        }
        String filenameHint = originalFilename;
        String altText = null;
        int id1 = id;
        int id2 = id;//+1;
        //no width specified
        org.docx4j.wml.P imageP = newImage(wordMLPackage, bytes, filenameHint, altText, id1, id2);
        wordMLPackage.getMainDocumentPart().addObject(imageP);
        org.docx4j.wml.P captionP = createCaption(LocalizeUtil
                .getLocalizedTextFromApplicationResources("admin.actions.exportDocx.figure", locale), id,
                originalFilename, description, captionStyleId, id);
        wordMLPackage.getMainDocumentPart().addObject(captionP);
        /*if (description!=null && !"".equals(description)) {
           org.docx4j.wml.P descriptionP =createImageDescription(description, captionStyleId);
           wordMLPackage.getMainDocumentPart().addObject(descriptionP);
        }*/
    }
    is.close();
}

From source file:net.pms.util.OpenSubtitle.java

public static String computeHash(File file) throws IOException {
    long size = file.length();
    FileInputStream fis = new FileInputStream(file);
    return computeHash(fis, size);
}

From source file:co.cask.cdap.gateway.util.Util.java

/**
 * Read the contents of a binary file into a byte array.
 *
 * @param filename The name of the file//  w  w  w  .java  2 s  .c  o  m
 * @return the content of the file if successful, otherwise null
 */
public static byte[] readBinaryFile(String filename) {
    File file = new File(filename);
    if (!file.isFile()) {
        System.err.println("'" + filename + "' is not a regular file.");
        return null;
    }
    int bytesToRead = (int) file.length();
    byte[] bytes = new byte[bytesToRead];
    int offset = 0;
    try {
        FileInputStream input = new FileInputStream(filename);
        while (bytesToRead > 0) {
            int bytesRead = input.read(bytes, offset, bytesToRead);
            bytesToRead -= bytesRead;
            offset += bytesRead;
        }
        input.close();
        return bytes;
    } catch (FileNotFoundException e) {
        LOG.error("File '" + filename + "' cannot be opened: " + e.getMessage());
    } catch (IOException e) {
        LOG.error("Error reading from file '" + filename + "': " + e.getMessage());
    }
    return bytes;
}

From source file:jetbrains.exodus.util.CompressBackupUtil.java

private static void doTar(String pathInArchive, File source, TarArchiveOutputStream tarOut) throws IOException {
    if (source.isDirectory()) {
        for (File file : IOUtil.listFiles(source)) {
            doTar(pathInArchive + source.getName() + File.separator, file, tarOut);
        }/*  w w  w.jav  a  2  s  .  co m*/
    } else {
        archiveFile(tarOut, pathInArchive, source, source.length());
    }
}

From source file:jeeves.server.sources.JeevletServiceRequestFactory.java

private static Element getMonoPartParams(Request req, String uploadDir, int maxUploadSize) throws Exception {
    Element params = new Element("params");

    Representation entity = req.getEntity();
    String name = entity.getDisposition().getFilename();
    String type = entity.getDisposition().getType();

    File uploadedFile = new File(uploadDir, name);
    entity.write(new FileOutputStream(uploadedFile));

    long size = uploadedFile.length();

    Element elem = new Element(name).setAttribute("type", "file").setAttribute("size", Long.toString(size))
            .setText(name);/*from   ww  w . j  a  va2s. co  m*/
    //
    if (type != null)
        elem.setAttribute("content-type", type);

    params.addContent(elem);

    return params;
}

From source file:Main.java

public static Uri getPhotoUri(Context context) {
    long currentTimeMillis = System.currentTimeMillis();
    Date today = new Date(currentTimeMillis);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String title = dateFormat.format(today);
    String dirPath = getDirPath(context);
    String fileName = "img_capture_" + title + ".jpg";
    String path = dirPath + "/" + fileName;
    File file = new File(path);
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, title);
    values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
    values.put(MediaStore.Images.Media.DATA, path);
    values.put(MediaStore.Images.Media.DATE_TAKEN, currentTimeMillis);
    if (file.exists()) {
        values.put(MediaStore.Images.Media.SIZE, file.length());
    }/*from w ww.  ja v  a2 s  .c o  m*/
    Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    return uri;
}

From source file:edu.cmu.cs.lti.util.general.BasicConvenience.java

public static byte[] readFileBytes(File file) throws IOException {
    InputStream stream = new BufferedInputStream(new FileInputStream(file));
    try {//from   ww w.j av a 2  s  .  co  m
        byte[] bytes = new byte[(int) file.length()];
        int off = 0;
        while (off < bytes.length) {
            int read = stream.read(bytes, off, bytes.length - off);
            off += read;
        }
        return bytes;
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}

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

public static void sendFileTest(File source, File target) throws Exception {
    FileInputStream fis = null;//from w w w  .  j  av  a  2 s. c o m
    FileOutputStream fos = null;
    try {
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);
        FileChannel sChannel = fis.getChannel();
        FileChannel tChannel = fos.getChannel();
        target.createNewFile();
        sChannel.transferTo(0, source.length(), tChannel);
        tChannel.close();
        sChannel.close();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.halseyburgund.roundware.server.RWHttpManager.java

public static String uploadFile(String page, Properties properties, String fileParam, String file)
        throws Exception {
    if (D) {//from  www.j  av  a2s .  c o m
        RWHtmlLog.i(TAG, "Starting upload of file: " + file, null);
    }

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);

    HttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost(page);
    MultipartEntity entity = new MultipartEntity();

    Iterator<Map.Entry<Object, Object>> i = properties.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) i.next();
        String key = (String) entry.getKey();
        String val = (String) entry.getValue();
        entity.addPart(key, new StringBody(val));
        if (D) {
            RWHtmlLog.i(TAG, "Added StringBody multipart for: '" + key + "' = '" + val + "'", null);
        }
    }

    File upload = new File(file);
    entity.addPart(fileParam, new FileBody(upload));
    if (D) {
        String msg = "Added FileBody multipart for: '" + fileParam + "' = <'" + upload.getAbsolutePath()
                + ", size: " + upload.length() + " bytes >'";
        RWHtmlLog.i(TAG, msg, null);
    }

    request.setEntity(entity);

    if (D) {
        RWHtmlLog.i(TAG, "Sending HTTP request...", null);
    }

    HttpResponse response = httpClient.execute(request);

    int st = response.getStatusLine().getStatusCode();

    if (st == HttpStatus.SC_OK) {
        StringBuffer sbResponse = new StringBuffer();
        InputStream content = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = reader.readLine()) != null) {
            sbResponse.append(line);
        }
        content.close(); // this will also close the connection

        if (D) {
            RWHtmlLog.i(TAG, "Upload successful (HTTP code: " + st + ")", null);
            RWHtmlLog.i(TAG, "Server response: " + sbResponse.toString(), null);
        }

        return sbResponse.toString();
    } else {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        entity.writeTo(ostream);
        RWHtmlLog.e(TAG, "Upload failed (http code: " + st + ")", null);
        RWHtmlLog.e(TAG, "Server response: " + ostream.toString(), null);
        throw new Exception(HTTP_POST_FAILED + st);
    }
}