Example usage for java.io FileInputStream read

List of usage examples for java.io FileInputStream read

Introduction

In this page you can find the example usage for java.io FileInputStream read.

Prototype

public int read(byte b[], int off, int len) throws IOException 

Source Link

Document

Reads up to len bytes of data from this input stream into an array of bytes.

Usage

From source file:JarUtils.java

/**
 * This recursive method writes all matching files and directories to
 * the jar output stream./*  w  ww. j a  v a 2  s  .  c  o m*/
 */
private static void jar(File src, String prefix, JarInfo info) throws IOException {

    JarOutputStream jout = info.out;
    if (src.isDirectory()) {
        // create / init the zip entry
        prefix = prefix + src.getName() + "/";
        ZipEntry entry = new ZipEntry(prefix);
        entry.setTime(src.lastModified());
        entry.setMethod(JarOutputStream.STORED);
        entry.setSize(0L);
        entry.setCrc(0L);
        jout.putNextEntry(entry);
        jout.closeEntry();

        // process the sub-directories
        File[] files = src.listFiles(info.filter);
        for (int i = 0; i < files.length; i++) {
            jar(files[i], prefix, info);
        }
    } else if (src.isFile()) {
        // get the required info objects
        byte[] buffer = info.buffer;

        // create / init the zip entry
        ZipEntry entry = new ZipEntry(prefix + src.getName());
        entry.setTime(src.lastModified());
        jout.putNextEntry(entry);

        // dump the file
        FileInputStream in = new FileInputStream(src);
        int len;
        while ((len = in.read(buffer, 0, buffer.length)) != -1) {
            jout.write(buffer, 0, len);
        }
        in.close();
        jout.closeEntry();
    }
}

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

/**
 * Identify a file, returning metadata//w  w  w. j a v  a 2  s  . co 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());
}

From source file:com.alibaba.otter.node.etl.common.io.compress.impl.PackableObject.java

/**
 * Compares a file to a list of packables and identifies an object by
 * header. If no matching header is found, it identifies the file by file
 * extension. If identification was not successfull, null is returned
 * //from w  ww. j a v  a  2s  .co  m
 * @param file the file to identify
 * @param packables a list of packables
 * @return a matching packable object, or null
 * @throws IOException
 */
public static PackableObject identifyByHeader(File file, List packables) throws IOException {
    FileInputStream fis = null;
    try {
        /* Archive result */
        // PackableObject packable = null;
        // identify archive by header
        fis = new FileInputStream(file);
        byte[] headerBytes = new byte[20];
        fis.read(headerBytes, 0, 20);

        Iterator iter = packables.iterator();
        while (iter.hasNext()) {
            PackableObject p = (PackableObject) iter.next();
            byte[] fieldHeader = p.getHeader();

            if (fieldHeader != null) {
                if (compareByteArrays(headerBytes, fieldHeader)) {
                    return p;
                }
            }
        }

        // if we couldn't find an archiver by header bytes, we'll give it a
        // try
        // with the default name extension. This is useful, cause some
        // archives
        // like tar have no header.
        String name = file.getName();
        String extension = null;
        String[] s = name.split("\\.");

        if (s.length > 1) {
            extension = s[s.length - 1];
        }

        Iterator it = packables.iterator();

        while (it.hasNext()) {
            PackableObject p = (PackableObject) it.next();
            if (p.isPackableWith(extension, PackableObject.CHOOSE_EXTENSION)) {
                return p;
            }
        }
        // No implementation found
        return null;
    } finally {
        IOUtils.closeQuietly(fis);
    }
}

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

public static void copyTest(File source, File target) throws Exception {
    FileInputStream fis = null;
    FileOutputStream fos = null;//from   w w  w  .  j a v a  2  s.  co  m
    try {
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);
        target.createNewFile();

        byte[] bytes = new byte[16 * 1024];
        int n = -1;
        while ((n = fis.read(bytes, 0, bytes.length)) > 0) {
            fos.write(bytes, 0, n);
        }

        fos.flush();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(fos);
    }
}

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

public static void createJarArchive(File jarFile, File[] listFiles) throws IOException {
    byte b[] = new byte[10240];
    FileOutputStream fout = new FileOutputStream(jarFile);
    JarOutputStream out = new JarOutputStream(fout, new Manifest());
    for (int i = 0; i < listFiles.length; i++) {
        if (listFiles[i] == null || !listFiles[i].exists() || listFiles[i].isDirectory()) {
            System.out.println();
        }/*  ww  w.  ja  va 2  s .  co m*/
        JarEntry addFiles = new JarEntry(listFiles[i].getName());
        addFiles.setTime(listFiles[i].lastModified());
        out.putNextEntry(addFiles);

        FileInputStream fin = new FileInputStream(listFiles[i]);
        while (true) {
            int len = fin.read(b, 0, b.length);
            if (len <= 0)
                break;
            out.write(b, 0, len);
        }
        fin.close();
    }
    out.close();
    fout.close();
}

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/*from   w  w w. jav a  2s .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:com.ca.dvs.app.dvs_servlet.misc.FileUtil.java

/**
 * A quick test to determine if uploaded file is a ZIP file
 * <p> //from   w  w  w  . j a  v a 2s .  c om
 * @param file the file to interrogate for being a zip file 
 * @return true is the specified file is a zip file
 * @throws IOException
 */
public static boolean isZipFile(File file) throws IOException {

    boolean isZipFile = false;
    FileInputStream fileInputStream = null;

    try {

        fileInputStream = new FileInputStream(file);

        if (fileInputStream.available() > ZIP_SIGNATURE.length) {

            byte[] magic = new byte[ZIP_SIGNATURE.length];

            if (ZIP_SIGNATURE.length == fileInputStream.read(magic, 0, ZIP_SIGNATURE.length)) {

                isZipFile = Arrays.equals(magic, ZIP_SIGNATURE);

            }

        }

    } finally {

        if (null != fileInputStream) {
            fileInputStream.close();
        }

    }

    return isZipFile;
}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

protected static void assembleMultipartFiles(DataOutputStream out, Map<String, String> vars,
        Map<String, File> files) throws IOException {
    for (String key : vars.keySet()) {
        out.writeBytes("--" + BOUNDARY + CRLF);
        out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + CRLF);
        out.writeBytes(CRLF);/*from w ww.java2s  .  co  m*/
        out.writeBytes(vars.get(key) + CRLF);
    }

    for (String key : files.keySet()) {
        File f = files.get(key);
        out.writeBytes("--" + BOUNDARY + CRLF);
        out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"; filename=\"" + f.getName() + "\""
                + CRLF);
        out.writeBytes("Content-Type: application/octet-stream" + CRLF);
        out.writeBytes(CRLF);

        // write file
        int maxBufferSize = 1024;
        FileInputStream fin = new FileInputStream(f);
        int bytesAvailable = fin.available();
        int bufferSize = Math.min(maxBufferSize, bytesAvailable);
        byte[] buffer = new byte[bufferSize];

        int bytesRead = fin.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            out.write(buffer, 0, bufferSize);
            bytesAvailable = fin.available();
            bufferSize = Math.min(maxBufferSize, bytesAvailable);
            bytesRead = fin.read(buffer, 0, bufferSize);
        }
    }
    out.writeBytes(CRLF);
    out.writeBytes("--" + BOUNDARY + "--" + CRLF);
    out.writeBytes(CRLF);
}

From source file:Main.java

private static byte[] getBytesFromFile(File file) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
    try {//  w w  w. jav  a 2 s  .c om
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        int maxBufferSize = 1024 * 1024;
        int bufferSize = (int) Math.min(file.getTotalSpace(), maxBufferSize);
        byte[] buffer = new byte[bufferSize];

        // read file and write it into form...
        int bytesRead = 0;

        if (fileInputStream != null) {
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        while (bytesRead > 0) {
            dataOutputStream.write(buffer, 0, bufferSize);
            int bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return byteArrayOutputStream.toByteArray();
}

From source file:org.webinos.android.util.ModuleUtils.java

public static boolean copyFile(File src, File dest) {
    boolean result = true;
    if (src.isDirectory()) {
        result = copyDir(src, dest);//from   w w w. j av a  2  s .  co m
    } else {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            int count;
            byte[] buf = new byte[1024];
            fis = new FileInputStream(src);
            fos = new FileOutputStream(dest);
            while ((count = fis.read(buf, 0, 1024)) != -1)
                fos.write(buf, 0, count);
        } catch (IOException e) {
            Log.v(TAG, "moveFile exception: aborting; exception: " + e + "; src = " + src.toString()
                    + "; dest = " + dest.toString());
            return false;
        } finally {
            try {
                if (fis != null)
                    fis.close();
                if (fos != null)
                    fos.close();
            } catch (IOException ieo) {
            }
        }
    }
    return result;
}