Example usage for java.io FileInputStream getChannel

List of usage examples for java.io FileInputStream getChannel

Introduction

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

Prototype

public FileChannel getChannel() 

Source Link

Document

Returns the unique java.nio.channels.FileChannel FileChannel object associated with this file input stream.

Usage

From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java

/**
 * Calculate content MD5 header values for feeds stored on disk.
 *//*w  ww .  j a  va2s.c  o  m*/
private String computeContentMD5HeaderValue(FileInputStream fis) throws IOException, NoSuchAlgorithmException {

    DigestInputStream dis = new DigestInputStream(fis, MessageDigest.getInstance("MD5"));

    byte[] buffer = new byte[8192];
    while (dis.read(buffer) > 0)
        ;

    String md5Content = new String(
            org.apache.commons.codec.binary.Base64.encodeBase64(dis.getMessageDigest().digest()));

    // Effectively resets the stream to be beginning of the file via a FileChannel.
    fis.getChannel().position(0);

    return md5Content;
}

From source file:com.example.sensingapp.SensingApp.java

private void copyWaveFile() {
    FileInputStream in = null;
    FileOutputStream out = null;/*from w w  w.ja  v a  2s .  com*/
    long totalAudioLen = 0;
    long totalDataLen = totalAudioLen + 36;
    int channels = 2;
    long byteRate = 16 * m_nAudioSampleRate * channels / 8;
    String sFullAudioPathFileTmp = m_sRecordFullPathFile + ".wav.tmp";
    String sFullAudioPathFile = m_sRecordFullPathFile + ".wav";

    byte[] data = new byte[m_nBufferSize];

    try {
        in = new FileInputStream(sFullAudioPathFileTmp);
        out = new FileOutputStream(sFullAudioPathFile);
        totalAudioLen = in.getChannel().size();
        totalDataLen = totalAudioLen + 36;

        WriteWaveFileHeader(out, totalAudioLen, totalDataLen, m_nAudioSampleRate, channels, byteRate);

        while (in.read(data) != -1) {
            out.write(data);
        }

        in.close();
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.skt.runtime.html5apis.file.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP multipart request.
 * @param source        Full path of the file on the file system
 * @param target        URL of the server to receive the file
 * @param args          JSON Array of args
 *
 * args[2] fileKey       Name of file request parameter
 * args[3] fileName      File name to be used on server
 * args[4] mimeType      Describes file content type
 * args[5] params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 *//*from   w  w  w  . java  2  s .  com*/
private PluginResult upload(String source, String target, JSONArray args) {
    Log.d(LOG_TAG, "upload " + source + " to " + target);

    HttpURLConnection conn = null;
    try {
        // Setup the options
        String fileKey = getArgument(args, 2, "file");
        String fileName = getArgument(args, 3, "image.jpg");
        String mimeType = getArgument(args, 4, "image/jpeg");
        JSONObject params = args.optJSONObject(5);
        if (params == null) {
            params = new JSONObject();
        }
        boolean trustEveryone = args.optBoolean(6);
        boolean chunkedMode = args.optBoolean(7) || args.isNull(7); //Always use chunked mode unless set to false as per API

        Log.d(LOG_TAG, "fileKey: " + fileKey);
        Log.d(LOG_TAG, "fileName: " + fileName);
        Log.d(LOG_TAG, "mimeType: " + mimeType);
        Log.d(LOG_TAG, "params: " + params);
        Log.d(LOG_TAG, "trustEveryone: " + trustEveryone);
        Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);

        // Create return object
        FileUploadResult result = new FileUploadResult();

        // Get a input stream of the file on the phone
        FileInputStream fileInputStream = (FileInputStream) getPathFromUri(source);

        DataOutputStream dos = null;

        int bytesRead, bytesAvailable, bufferSize;
        long totalBytes;
        byte[] buffer;
        int maxBufferSize = 8096;

        //------------------ CLIENT REQUEST
        // open a URL connection to the server
        URL url = new URL(target);

        // Open a HTTP connection to the URL based on protocol
        if (url.getProtocol().toLowerCase().equals("https")) {
            // Using standard HTTPS connection. Will not allow self signed certificate
            if (!trustEveryone) {
                conn = (HttpsURLConnection) url.openConnection();
            }
            // Use our HTTPS connection that blindly trusts everyone.
            // This should only be used in debug environments
            else {
                // Setup the HTTPS connection class to trust everyone
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                // Save the current hostnameVerifier
                defaultHostnameVerifier = https.getHostnameVerifier();
                // Setup the connection not to verify hostnames
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            }
        }
        // Return a standard HTTP connection
        else {
            conn = (HttpURLConnection) url.openConnection();
        }

        // Allow Inputs
        conn.setDoInput(true);

        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        // Handle the other headers
        try {
            JSONObject headers = params.getJSONObject("headers");
            for (Iterator iter = headers.keys(); iter.hasNext();) {
                String headerKey = iter.next().toString();
                conn.setRequestProperty(headerKey, headers.getString(headerKey));
            }
        } catch (JSONException e1) {
            // No headers to be manipulated!
        }

        // Set the cookies on the response
        String cookie = CookieManager.getInstance().getCookie(target);
        if (cookie != null) {
            conn.setRequestProperty("Cookie", cookie);
        }

        /*
        * Store the non-file portions of the multipart data as a string, so that we can add it
        * to the contentSize, since it is part of the body of the HTTP request.
        */
        String extraParams = "";
        try {
            for (Iterator iter = params.keys(); iter.hasNext();) {
                Object key = iter.next();
                if (!String.valueOf(key).equals("headers")) {
                    extraParams += LINE_START + BOUNDARY + LINE_END;
                    extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
                    extraParams += LINE_END + LINE_END;
                    extraParams += params.getString(key.toString());
                    extraParams += LINE_END;
                }
            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }

        extraParams += LINE_START + BOUNDARY + LINE_END;
        extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"";

        String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
        String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;

        // Should set this up as an option
        if (chunkedMode) {
            conn.setChunkedStreamingMode(maxBufferSize);
        } else {
            int stringLength = extraParams.getBytes("UTF-8").length + midParams.getBytes("UTF-8").length
                    + tailParams.getBytes("UTF-8").length + fileName.getBytes("UTF-8").length;
            Log.d(LOG_TAG, "String Length: " + stringLength);
            int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
            Log.d(LOG_TAG, "Content Length: " + fixedLength);
            conn.setFixedLengthStreamingMode(fixedLength);
        }

        dos = new DataOutputStream(conn.getOutputStream());
        dos.write(extraParams.getBytes("UTF-8"));
        //We don't want to chagne encoding, we just want this to write for all Unicode.
        dos.write(fileName.getBytes("UTF-8"));
        dos.write(midParams.getBytes("UTF-8"));

        // create a buffer of maximum size
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        totalBytes = 0;

        while (bytesRead > 0) {
            totalBytes += bytesRead;
            result.setBytesSent(totalBytes);
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.write(tailParams.getBytes("UTF-8"));

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();

        //------------------ read the SERVER RESPONSE
        StringBuffer responseString = new StringBuffer("");
        DataInputStream inStream;
        try {
            inStream = new DataInputStream(conn.getInputStream());
        } catch (FileNotFoundException e) {
            Log.e(LOG_TAG, e.toString(), e);
            throw new IOException("Received error from server");
        }

        String line;
        while ((line = inStream.readLine()) != null) {
            responseString.append(line);
        }
        Log.d(LOG_TAG, "got response from server");
        Log.d(LOG_TAG, responseString.toString());

        // send request and retrieve response
        result.setResponseCode(conn.getResponseCode());
        result.setResponse(responseString.toString());

        inStream.close();

        // Revert back to the proper verifier and socket factories
        if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
            ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
            HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
        }

        Log.d(LOG_TAG, "****** About to return a result from upload");
        return new PluginResult(PluginResult.Status.OK, result.toJSONObject());

    } catch (FileNotFoundException e) {
        JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (MalformedURLException e) {
        JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (IOException e) {
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.e(LOG_TAG, error.toString(), e);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    } catch (Throwable t) {
        // Shouldn't happen, but will
        JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
        Log.wtf(LOG_TAG, error.toString(), t);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:es.pode.publicacion.negocio.servicios.SrvPublicacionServiceImpl.java

/**
 * Mueve el contenido de un directorio a otro directorio.
 * // w ww . j a  va 2s .  com
 * @param oldDir
 *            Directorio origen.
 * @param newDir
 *            Directorio destino.
 * @return devuelve el tamanio del directorio movido.
 * @throws Exception
 * 
 */
protected Long handleMoveDir(File oldDir, File newDir) throws IOException {
    long longitudTransferida = 0;
    if (oldDir.isDirectory()) {
        newDir.mkdirs();
        String list[] = oldDir.list();

        for (int i = 0; i < list.length; i++) {
            String dest1 = newDir.getAbsolutePath() + "/" + list[i];
            String src1 = oldDir.getAbsolutePath() + "/" + list[i];
            longitudTransferida += handleMoveDir(new File(src1), new File(dest1)).longValue();
        }
    } else {
        FileInputStream fin = new FileInputStream(oldDir);
        FileOutputStream fos = new FileOutputStream(newDir);

        FileChannel sourceChannel = fin.getChannel();
        FileChannel targetChannel = fos.getChannel();
        longitudTransferida = sourceChannel.size();
        sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
        sourceChannel.close();
        targetChannel.close();
    }
    return new Long(longitudTransferida);
}

From source file:gephi.spade.panel.fcsFile.java

/**
 * readFile ---// w  w  w . j  a va 2  s  .  com
 * <p>
 * A helper function to read all the fields in the TEXT segment of the FCS
 * file.
 * </p>
 *
 * <p>
 * This helper function should only be called once by the constructor as it
 * is quite expensive.
 * </p>
 *
 * @param extractEventsP
 *            boolean flag indicating whether to extract events in the
 *            underlying file.
 * @throws <code>java.io.FileNotFoundException</code> if the file is not
 *         found.
 * @throws <code>java.io.IOException</code> if an IO exception occurred.
 */
private void readFile(boolean extractEventsP) throws FileNotFoundException, IOException {
    // Open a file input stream to the file
    FileInputStream fis = new FileInputStream(file);

    // Create a byte array to hold the version
    byte[] versionArray = new byte[VERSION_SIZE];

    // Read the version into the byte array
    int numRead = fis.read(versionArray);

    if (numRead < VERSION_SIZE) {
        // If the number of bytes read is less than the number of bytes in
        // the version string, then the file is too small to be an FCS file.
        isFCSP = false;

        // Close the file input stream
        fis.close();

        // Quit
        return;
    }

    // Decode the version using the default encoding
    version = new String(versionArray);

    // Determine whether the file is an FCS file by whether the version
    // string starts with the FCS_PREFIX
    isFCSP = version.startsWith(FCS_PREFIX);

    if (!isFCSP) {
        // If the file is not an FCS file, then close the file and quit.
        // Close the file input stream
        fis.close();

        // Quit
        return;
    }

    /**
     * At this point, we are pretty sure that the file is an FCS file. So,
     * we parse it.
     */
    /**
     * Get the standard HEADER stuff
     */
    // Skip 4 bytes to get to byte 10
    fis.skip(4);

    // Create a byte array to hold the HEADER
    byte[] headerArray = new byte[48];

    // Read the header into the byte array
    numRead = fis.read(headerArray);

    if (numRead < 48) {
        // If the number of bytes read is less than 48, then the file is too
        // small to be an FCS file.
        isFCSP = false;

        // Close the file input stream
        fis.close();

        // Quit
        return;
    }

    try {
        // Try to parse the TEXT segment start and end and DATA segment
        // start and end
        textStart = Integer.parseInt((new String(headerArray, 0, 8)).trim());
        textEnd = Integer.parseInt((new String(headerArray, 8, 8)).trim());
        dataStart = Integer.parseInt((new String(headerArray, 16, 8)).trim());
        dataEnd = Integer.parseInt((new String(headerArray, 24, 8)).trim());
    } catch (NumberFormatException nfe) {
        // If a NumberFormatException occured, then quit because there's
        // nothing we can do without the TEXT or DATA segment.
        // Close the file input stream
        fis.close();

        return;
    }

    /**
     * Get the ANALYSIS segment limits
     */
    try {
        // Try to parse the analysisStart and analysisEnd
        analysisStart = Integer.parseInt((new String(headerArray, 32, 8)).trim());
        analysisEnd = Integer.parseInt((new String(headerArray, 40, 8)).trim());
    } catch (NumberFormatException nfe) {
        // If a NumberFormatException occured, then set the ANALYSIS start
        // and end to 0 since this segment is optional.
        analysisStart = 0;
        analysisEnd = 0;
    }

    /**
     * Use NIO to read the OTHER and TEXT segments
     */
    // Get the channel for the input file
    FileChannel fc = fis.getChannel();

    // Move the channel's position back to 0
    fc.position(0);

    // Map the TEXT segment to memory
    MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, textEnd + 1);

    /**
     * Create the character decoder for parsing characters
     */
    decoder = charset.newDecoder();

    /**
     * Get the OTHER segment
     */
    mbb.limit(textStart);
    mbb.position(58);
    CharBuffer other = decoder.decode(mbb.slice());

    /**
     * Get the TEXT segment
     */
    mbb.limit(textEnd + 1);
    mbb.position(textStart);
    text = decoder.decode(mbb.slice()).toString();

    /**
     * Close the file since we have the string version of the TEXT segment
     */
    // Close the file channel
    fc.close();

    // Close the file input stream
    fis.close();

    /**
     * Decode the TEXT segment
     */
    // The first character of the primary TEXT segment contains the
    // delimiter character
    delimiter = text.charAt(0);

    /**
     * Key/Value Pairs
     */
    // Generate all the pairs
    String[] pairs;

    if (delimiter == '\\') {
        // If the delimiter character is a backslash, then we have to escape
        // it in the regular expression.
        pairs = text.split("[\\\\]");
    } else {
        // Otherwise, we can just split it normally by using the character
        // in the regular expression.
        pairs = text.split("[" + Character.toString(delimiter) + "]");
    }

    /**
     * Calculate the number of pairs --- The number of pairs is the length
     * of the pairs array minus 1 divided by 2. The one is due to the empty
     * first element from the Java split above.
     */
    int numPairs = (pairs.length - 1) / 2;

    // Create a mapping for each key and its value
    settings = new Properties();

    // Loop through the TEXT segment we just split to get the keys and
    // values
    // The key is in (i * 2) + 1 to account for the empty first element.
    // The value is in (i * 2) + 2 to account for the empty first element.
    for (int i = 0; i < numPairs; i++) {
        settings.setProperty(pairs[(i * 2) + 1].trim(), pairs[(i * 2) + 2].trim());
    }

    // Go through all the key/value pairs and parse them
    parseSettings();

    /**
     * Extract Events
     */
    if (extractEventsP) {
        // If we are extracting data, then do so.
        extractEvents();
    }
}

From source file:com.zoffcc.applications.zanavi.Navit.java

private void import_map_points_from_sdcard() {
    String orig_file = NAVIT_DATA_SHARE_DIR + Navit_DEST_FILENAME;
    String dest_file_dir = CFG_FILENAME_PATH + "../export/";

    try {//from w ww . j a v  a2s. c  o m
        File source = new File(dest_file_dir + Navit_DEST_FILENAME);
        File destination = new File(orig_file);

        if (source.exists()) {
            FileInputStream fi = new FileInputStream(source);
            FileOutputStream fo = new FileOutputStream(destination);
            FileChannel src = fi.getChannel();
            FileChannel dst = fo.getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
            fi.close();
            fo.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    read_map_points();
}

From source file:com.zoffcc.applications.zanavi.Navit.java

private void export_map_points_to_sdcard() {
    String orig_file = NAVIT_DATA_SHARE_DIR + Navit_DEST_FILENAME;
    String dest_file_dir = CFG_FILENAME_PATH + "../export/";

    try {//from   w  w  w.j av a 2 s.c  o m
        File dir = new File(dest_file_dir);
        dir.mkdirs();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        File source = new File(orig_file);
        File destination = new File(dest_file_dir + Navit_DEST_FILENAME);

        if (source.exists()) {
            FileInputStream fi = new FileInputStream(source);
            FileOutputStream fo = new FileOutputStream(destination);
            FileChannel src = fi.getChannel();
            FileChannel dst = fo.getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
            fi.close();
            fo.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.sakaiproject.assignment.tool.AssignmentAction.java

private byte[] readIntoBytes(InputStream zin, String fName, long length) throws IOException {

    byte[] buffer = new byte[4096];

    File f = File.createTempFile("asgnup", "tmp");

    FileOutputStream fout = new FileOutputStream(f);
    try {//from  w  w  w  . j  av a2 s. c  o m
        int len;
        while ((len = zin.read(buffer)) > 0) {
            fout.write(buffer, 0, len);
        }
        zin.close();
    } finally {
        try {
            fout.close(); // The file channel needs to be closed before the deletion.
        } catch (IOException ioException) {
            M_log.warn(this + "readIntoBytes: problem closing FileOutputStream " + ioException.getMessage());
        }
    }

    FileInputStream fis = new FileInputStream(f);
    FileChannel fc = fis.getChannel();
    byte[] data = null;
    try {
        data = new byte[(int) (fc.size())]; // fc.size returns the size of the file which backs the channel
        ByteBuffer bb = ByteBuffer.wrap(data);
        fc.read(bb);
    } finally {
        try {
            fc.close(); // The file channel needs to be closed before the deletion.
        } catch (IOException ioException) {
            M_log.warn(this + "readIntoBytes: problem closing FileChannel " + ioException.getMessage());
        }

        try {
            fis.close(); // The file inputstream needs to be closed before the deletion.
        } catch (IOException ioException) {
            M_log.warn(this + "readIntoBytes: problem closing FileInputStream " + ioException.getMessage());
        }
    }

    //remove the file
    f.delete();

    return data;
}

From source file:com.clark.func.Functions.java

/**
 * Internal copy file method.//from  www. j av  a  2 s .  co  m
 * 
 * @param srcFile
 *            the validated source file, must not be <code>null</code>
 * @param destFile
 *            the validated destination file, must not be <code>null</code>
 * @param preserveFileDate
 *            whether to preserve the file date
 * @throws IOException
 *             if an error occurs
 */
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
    if (destFile.exists() && destFile.isDirectory()) {
        throw new IOException("Destination '" + destFile + "' exists but is a directory");
    }

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        input = fis.getChannel();
        output = fos.getChannel();
        long size = input.size();
        long pos = 0;
        long count = 0;
        while (pos < size) {
            count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
            pos += output.transferFrom(input, pos, count);
        }
    } finally {
        closeQuietly(output);
        closeQuietly(fos);
        closeQuietly(input);
        closeQuietly(fis);
    }

    if (srcFile.length() != destFile.length()) {
        throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
    }
    if (preserveFileDate) {
        destFile.setLastModified(srcFile.lastModified());
    }
}