Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

Usage

From source file:com.panet.imeta.core.row.ValueDataUtil.java

public static String createChecksum(ValueMetaInterface metaA, Object dataA, String type) {
    String md5Hash = null;//  w  ww.j  av  a 2s .co m
    FileInputStream in = null;
    try {
        in = new FileInputStream(dataA.toString());
        int bytes = in.available();
        byte[] buffer = new byte[bytes];
        in.read(buffer);

        StringBuffer md5HashBuff = new StringBuffer(32);
        byte[] b = MessageDigest.getInstance(type).digest(buffer);
        int len = b.length;
        for (int x = 0; x < len; x++) {
            md5HashBuff.append(String.format("%02x", b[x]));
        }

        md5Hash = md5HashBuff.toString();

    } catch (Exception e) {
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (Exception e) {
        }
        ;
    }

    return md5Hash;
}

From source file:gcm.play.android.samples.com.gcm.UnRegisterIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    //SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    try {//from ww w  . j  ava 2 s  .c  om
        // [START register_for_gcm]
        // Initially this call goes out to the network to retrieve the token, subsequent calls
        // are local.
        // [START get_token]
        //  InstanceID instanceID = InstanceID.getInstance(this);
        // String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
        //        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

        FileInputStream in = openFileInput("token.txt");

        InputStreamReader inputStreamReader = new InputStreamReader(in);
        byte[] data = new byte[in.available()];
        in.read(data, 0, in.available());
        token = new String(data, "UTF-8");
        Log.e(TAG, "token:'" + token + "'");
        // [END get_token]
        Log.i(TAG, "GCM Registration Token: " + token);
        this.token = token;
        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(token);

        // Subscribe to topic channels
        unsubscribeTopics(token);

        // You should store a boolean that indicates whether the generated token has been
        // sent to your server. If the boolean is false, send the token to your server,
        // otherwise your server should have already received the token.
        //sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
        // [END register_for_gcm]
    } catch (Exception e) {
        Log.d(TAG, "Failed to complete token refresh", e);
        // If an exception happens while fetching the new token or updating our registration data
        // on a third-party server, this ensures that we'll attempt the update at a later time.
        //sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false).apply();
    }
    // Notify UI that registration has completed, so the progress indicator can be hidden.
    Intent unregistrationComplete = new Intent(QuickstartPreferences.UNREGISTRATION_COMPLETE);
    LocalBroadcastManager.getInstance(this).sendBroadcast(unregistrationComplete);
}

From source file:com.digitalarx.android.syncadapter.ContactSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {//from www .j  a v  a  2 s  .co  m
    setAccount(account);
    setContentProviderClient(provider);
    Cursor c = getLocalContacts(false);
    if (c.moveToFirst()) {
        do {
            String lookup = c.getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
            String a = getAddressBookUri();
            String uri = a + lookup + ".vcf";
            FileInputStream f;
            try {
                f = getContactVcard(lookup);
                HttpPut query = new HttpPut(uri);
                byte[] b = new byte[f.available()];
                f.read(b);
                query.setEntity(new ByteArrayEntity(b));
                fireRawRequest(query);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            } catch (OperationCanceledException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (AuthenticatorException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } while (c.moveToNext());
        // } while (c.moveToNext());
    }

}

From source file:org.torproject.ernie.db.BridgeSnapshotReader.java

public BridgeSnapshotReader(BridgeDescriptorParser bdp, String bridgeDirectoriesDir) {
    Logger logger = Logger.getLogger(BridgeSnapshotReader.class.getName());
    SortedSet<String> parsed = new TreeSet<String>();
    File bdDir = new File(bridgeDirectoriesDir);
    File pbdFile = new File("stats/parsed-bridge-directories");
    boolean modified = false;
    if (bdDir.exists()) {
        if (pbdFile.exists()) {
            logger.fine("Reading file " + pbdFile.getAbsolutePath() + "...");
            try {
                BufferedReader br = new BufferedReader(new FileReader(pbdFile));
                String line = null;
                while ((line = br.readLine()) != null) {
                    parsed.add(line);//  ww  w .j  ava  2s . com
                }
                br.close();
                logger.fine("Finished reading file " + pbdFile.getAbsolutePath() + ".");
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed reading file " + pbdFile.getAbsolutePath() + "!", e);
                return;
            }
        }
        logger.fine("Importing files in directory " + bridgeDirectoriesDir + "/...");
        Stack<File> filesInInputDir = new Stack<File>();
        filesInInputDir.add(bdDir);
        while (!filesInInputDir.isEmpty()) {
            File pop = filesInInputDir.pop();
            if (pop.isDirectory()) {
                for (File f : pop.listFiles()) {
                    filesInInputDir.add(f);
                }
            } else if (!parsed.contains(pop.getName())) {
                try {
                    FileInputStream in = new FileInputStream(pop);
                    if (in.available() > 0) {
                        GzipCompressorInputStream gcis = new GzipCompressorInputStream(in);
                        TarArchiveInputStream tais = new TarArchiveInputStream(gcis);
                        BufferedInputStream bis = new BufferedInputStream(tais);
                        String fn = pop.getName();
                        String dateTime = fn.substring(11, 21) + " " + fn.substring(22, 24) + ":"
                                + fn.substring(24, 26) + ":" + fn.substring(26, 28);
                        while ((tais.getNextTarEntry()) != null) {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            int len;
                            byte[] data = new byte[1024];
                            while ((len = bis.read(data, 0, 1024)) >= 0) {
                                baos.write(data, 0, len);
                            }
                            byte[] allData = baos.toByteArray();
                            if (allData.length == 0) {
                                continue;
                            }
                            String ascii = new String(allData, "US-ASCII");
                            BufferedReader br3 = new BufferedReader(new StringReader(ascii));
                            String firstLine = null;
                            while ((firstLine = br3.readLine()) != null) {
                                if (firstLine.startsWith("@")) {
                                    continue;
                                } else {
                                    break;
                                }
                            }
                            if (firstLine.startsWith("r ")) {
                                bdp.parse(allData, dateTime, false);
                            } else {
                                int start = -1, sig = -1, end = -1;
                                String startToken = firstLine.startsWith("router ") ? "router " : "extra-info ";
                                String sigToken = "\nrouter-signature\n";
                                String endToken = "\n-----END SIGNATURE-----\n";
                                while (end < ascii.length()) {
                                    start = ascii.indexOf(startToken, end);
                                    if (start < 0) {
                                        break;
                                    }
                                    sig = ascii.indexOf(sigToken, start);
                                    if (sig < 0) {
                                        break;
                                    }
                                    sig += sigToken.length();
                                    end = ascii.indexOf(endToken, sig);
                                    if (end < 0) {
                                        break;
                                    }
                                    end += endToken.length();
                                    byte[] descBytes = new byte[end - start];
                                    System.arraycopy(allData, start, descBytes, 0, end - start);
                                    bdp.parse(descBytes, dateTime, false);
                                }
                            }
                        }
                    }
                    in.close();

                    /* Let's give some memory back, or we'll run out of it. */
                    System.gc();

                    parsed.add(pop.getName());
                    modified = true;
                } catch (IOException e) {
                    logger.log(Level.WARNING, "Could not parse bridge snapshot " + pop.getName() + "!", e);
                    continue;
                }
            }
        }
        logger.fine("Finished importing files in directory " + bridgeDirectoriesDir + "/.");
        if (!parsed.isEmpty() && modified) {
            logger.fine("Writing file " + pbdFile.getAbsolutePath() + "...");
            try {
                pbdFile.getParentFile().mkdirs();
                BufferedWriter bw = new BufferedWriter(new FileWriter(pbdFile));
                for (String f : parsed) {
                    bw.append(f + "\n");
                }
                bw.close();
                logger.fine("Finished writing file " + pbdFile.getAbsolutePath() + ".");
            } catch (IOException e) {
                logger.log(Level.WARNING, "Failed writing file " + pbdFile.getAbsolutePath() + "!", e);
            }
        }
    }
}

From source file:uk.org.openeyes.diagnostics.LegacyFieldProcessor.java

/**
 * Transfer the specified report./* w w  w  . j av a2 s. c o m*/
 *
 * @param patientRef
 * @param file
 * @param xmlFile
 * @param fieldReport
 */
private void transferLegacyHumphreyVisualField(File xmlFile, File file, FieldReport fieldReport)
        throws IOException {

    // execute the operation
    File imageConverted = new File(file.getParentFile(), FilenameUtils.getBaseName(file.getName()) + ".gif");
    File imageCropped = new File(file.getParentFile(),
            FilenameUtils.getBaseName(file.getName()) + "-cropped.gif");
    transformImages(file, imageConverted, imageCropped);
    BASE64Encoder encoder = new BASE64Encoder();
    FileInputStream fis = new FileInputStream(imageConverted);
    String encodedData = encoder.encode(IOUtils.toByteArray(fis, fis.available()));

    fis = new FileInputStream(imageCropped);
    String encodedDataThumb = encoder.encode(IOUtils.toByteArray(fis, fis.available()));

    String reportText = this.getHumphreyMeasurement(xmlFile,
            "__OE_PATIENT_ID_" + String.format("%07d", new Integer(fieldReport.getPatientId())) + "__",
            fieldReport, encodedData, encodedDataThumb);

    File f2 = new File(this.getLegacyDir(), FilenameUtils.getBaseName(file.getName()) + ".fmes");
    f2.createNewFile();
    FileUtils.write(f2, reportText);
    imageConverted.delete();
    imageCropped.delete();

}

From source file:br.com.bluesoft.pronto.controller.SprintController.java

@RequestMapping("/sprint/imagem.action")
public String imagem(final HttpServletResponse response, final int sprintKey) throws Exception {

    final String folderPath = Config.getImagesFolder() + "/sprints/";

    final File arquivo = new File(folderPath + sprintKey);

    final byte[] bytes;
    if (arquivo.exists()) {
        final FileInputStream fis = new FileInputStream(arquivo);
        final int numberBytes = fis.available();
        bytes = new byte[numberBytes];
        fis.read(bytes);//  w  w  w .  ja va  2s.  com
        fis.close();
    } else {
        final InputStream resource = this.getClass().getResourceAsStream("/noImage.jpg");
        final int numberBytes = resource.available();
        bytes = new byte[numberBytes];
        resource.read(bytes);
        resource.close();
    }

    response.getOutputStream().write(bytes);
    return null;

}

From source file:android.util.AtomicFile.java

/**
 * A convenience for {@link #openRead()} that also reads all of the
 * file contents into a byte array which is returned.
 *//*w  w  w  . j a  v  a  2  s. c o  m*/
public byte[] readFully() throws IOException {
    FileInputStream stream = openRead();
    try {
        int pos = 0;
        int avail = stream.available();
        byte[] data = new byte[avail];
        while (true) {
            int amt = stream.read(data, pos, data.length - pos);
            //Log.i("foo", "Read " + amt + " bytes at " + pos
            //        + " of avail " + data.length);
            if (amt <= 0) {
                //Log.i("foo", "**** FINISHED READING: pos=" + pos
                //        + " len=" + data.length);
                return data;
            }
            pos += amt;
            avail = stream.available();
            if (avail > data.length - pos) {
                byte[] newData = new byte[pos + avail];
                System.arraycopy(data, 0, newData, 0, pos);
                data = newData;
            }
        }
    } finally {
        stream.close();
    }
}

From source file:com.twinflag.coofiletouch.AuthorityUtil.java

public boolean isAuthorityExpired() {
    boolean retValue = true;
    if (DeviceUtil.isSdCardExist()) {
        String deviceInfo = null;
        String licenseFileContent = null;
        String decodedContent = null;
        String validContent = null;
        String dateInfo = null;/*from   w w  w.j a v a2s  .c  o m*/
        String deviceInfoTmp = null;
        String decodeKey = null;
        String lincenseFileFullName = null;
        String lincenseFileName = null;
        deviceInfo = DeviceUtil.getDeviceInfo();
        lincenseFileName = deviceInfo + ".license";
        // deviceInfo = "6523-8769-2234-85746873";
        // lincenseFileName = "6523-8769-2234-85746873.license";
        lincenseFileFullName = CoofileTouchApplication.getAppResBasePath() + File.separator
                + Constant.APP_RES_AUTHORITY_FOLDER + File.separator + lincenseFileName;
        deviceInfoTmp = deviceInfo.replace("-", "");
        if (deviceInfoTmp.length() >= LICENSE_DECODE_KEY_LEN)
            decodeKey = deviceInfoTmp.substring(deviceInfoTmp.length() - LICENSE_DECODE_KEY_LEN,
                    deviceInfoTmp.length());
        File authFile = new File(lincenseFileFullName);
        if (authFile.exists()) {
            try {
                FileInputStream fin = new FileInputStream(authFile);
                int length = fin.available();
                byte[] buffer = new byte[length];
                fin.read(buffer);
                licenseFileContent = EncodingUtils.getString(buffer, "UTF-8");
                fin.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (licenseFileContent != null) {
                try {
                    decodedContent = DES.decryptDES(licenseFileContent, decodeKey);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (decodedContent.length() >= DEVICE_INFO_CONTENT_LEN) {
                    validContent = decodedContent.substring(0, 10)
                            + decodedContent.substring(17, decodedContent.length());
                    dateInfo = decodedContent.substring(10, 16);
                    if (validContent.equalsIgnoreCase(deviceInfo) && isLaterThanToday(dateInfo)) {
                        retValue = false;
                    }
                }
            }
        }

    }
    return retValue;
}

From source file:org.efaps.esjp.archives.Version_Base.java

/**
 * Upload a Version. Moves the current File to a version and the new File into the current.
 *
 * @param _parameter Parameter as passed by the eFaps API.
 * @return new Return/*ww  w. j a  v a  2 s. c o m*/
 * @throws EFapsException on error
 */
public Return upload(final Parameter _parameter) throws EFapsException {
    final Context.FileParameter fileItem = Context.getThreadContext().getFileParameters().get("upload");
    if (fileItem != null) {
        try {
            final String name = _parameter.getParameterValue("name");
            final Instance current = _parameter.getCallInstance();
            // create a new Version
            final Insert insert = new Insert(CIArchives.Version);
            insert.add(CIArchives.Version.FileLink, current.getId());
            insert.execute();
            final Instance version = insert.getInstance();
            // get the current file, put it in termporary file and then check it in again
            final Checkout checkout = new Checkout(current);
            final InputStream currentStream = checkout.execute();
            final File temp = new FileUtil().getFile(checkout.getFileName());
            final OutputStream out = new FileOutputStream(temp);
            IOUtils.copy(currentStream, out);
            currentStream.close();
            out.close();
            final FileInputStream in = new FileInputStream(temp);
            // checkin  the current as version
            final Checkin versionCheckin = new Checkin(version);
            versionCheckin.execute(checkout.getFileName(), in, in.available());
            in.close();
            // override the current with new file
            final Checkin checkin = new Checkin(current);
            checkin.execute(name, fileItem.getInputStream(), (int) fileItem.getSize());
        } catch (final IOException e) {
            throw new EFapsException(this.getClass(), "execute", e, _parameter);
        }
    }
    return new Return();
}

From source file:Main.java

public static String postMultiPart(String urlTo, String post, String filepath, String filefield)
        throws ParseException, IOException {
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    String lineEnd = "\r\n";

    String result = "";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    String[] q = filepath.split("/");
    int idx = q.length - 1;

    try {/*from  w  w  w  . ja v  a  2  s.  c  om*/
        File file = new File(filepath);
        FileInputStream fileInputStream = new FileInputStream(file);

        URL url = new URL(urlTo);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\""
                + q[idx] + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);

        // Upload POST Data
        String[] posts = post.split("&");
        int max = posts.length;
        for (int i = 0; i < max; i++) {
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            String[] kv = posts[i].split("=");
            outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(kv[1]);
            outputStream.writeBytes(lineEnd);
        }

        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        inputStream = connection.getInputStream();
        result = convertStreamToString(inputStream);

        fileInputStream.close();
        inputStream.close();
        outputStream.flush();
        outputStream.close();

        return result;
    } catch (Exception e) {
        Log.e("MultipartRequest", "Multipart Form Upload Error");
        e.printStackTrace();
        return "error";
    }
}