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() throws IOException 

Source Link

Document

Reads a byte of data from this input stream.

Usage

From source file:com.monitor.baseservice.utils.XCodeUtil.java

public synchronized static byte[] loadBytes(String name) throws IOException {
    FileInputStream in = null;
    in = new FileInputStream(name);
    try {/*from  w  w w . ja  va2 s  .  co  m*/
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int ch;
        while ((ch = in.read()) != -1) {
            buffer.write(ch);
        }
        return buffer.toByteArray();
    } finally {
        in.close();
    }
}

From source file:com.aurel.track.lucene.util.FileUtil.java

public static byte[] getBytes(File file) throws IOException {
    if (file == null || !file.exists()) {
        return null;
    }/*from   w  w w.  ja  v  a  2  s .  c om*/

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    FileInputStream in = new FileInputStream(file);

    int c = in.read();

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

    in.close();
    out.close();

    return out.toByteArray();
}

From source file:com.clutch.ClutchSync.java

public static void sync(ClutchStats clutchStats) {
    if (thisIsHappening) {
        return;// w  ww  . j  a va  2 s .  c o m
    }
    thisIsHappening = true;
    if (pendingReload) {
        pendingReload = false;
        for (ClutchView clutchView : clutchViews) {
            clutchView.contentChanged();
        }
    }
    ClutchAPIClient.callMethod("sync", null, new ClutchAPIResponseHandler() {
        @Override
        public void onSuccess(JSONObject response) {
            final AssetManager mgr = context.getAssets();

            File parentCacheDir = context.getCacheDir();
            final File tempDir;
            try {
                tempDir = File.createTempFile("clutchtemp", Long.toString(System.nanoTime()), parentCacheDir);
                if (!tempDir.delete()) {
                    Log.e(TAG, "Could not delete temp file: " + tempDir.getAbsolutePath());
                    return;
                }
                if (!tempDir.mkdir()) {
                    Log.e(TAG, "Could not create temp directory: " + tempDir.getAbsolutePath());
                    return;
                }
            } catch (IOException e) {
                Log.e(TAG, "Could not create temp file");
                return;
            }

            File cacheDir = getCacheDir();
            if (cacheDir == null) {
                try {
                    if (!copyAssetDir(mgr, tempDir)) {
                        return;
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Couldn't copy the asset dir files to the temp dir: " + e);
                    return;
                }
            } else {
                try {
                    if (!copyDir(cacheDir, tempDir)) {
                        return;
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Couldn't copy the cache dir files to the temp dir: " + e);
                    return;
                }
            }

            conf = response.optJSONObject("conf");
            String version = "" + conf.optInt("_version");
            newFilesDownloaded = false;
            try {
                JSONCompareResult confCompare = JSONCompare.compareJSON(ClutchConf.getConf(), conf,
                        JSONCompareMode.NON_EXTENSIBLE);
                if (confCompare.failed()) {
                    newFilesDownloaded = true;
                    // This is where in the ObjC version we write out the conf, but I don't think we need to anymore
                }
            } catch (JSONException e1) {
                Log.i(TAG, "Couldn't compare the conf file with the cached conf file: " + e1);
            }

            File cachedFiles = new File(tempDir, "__files.json");
            JSONObject cached = null;
            if (cachedFiles.exists()) {
                StringBuffer strContent = new StringBuffer("");
                try {
                    FileInputStream in = new FileInputStream(cachedFiles);
                    int ch;
                    while ((ch = in.read()) != -1) {
                        strContent.append((char) ch);
                    }
                    in.close();
                    cached = new JSONObject(new JSONTokener(strContent.toString()));
                } catch (IOException e) {
                    Log.e(TAG, "Could not read __files.json from cache file: " + e);
                } catch (JSONException e) {
                    Log.e(TAG, "Could not parse __files.json from cache file: " + e);
                }
            }
            if (cached == null) {
                cached = new JSONObject();
            }

            final JSONObject files = response.optJSONObject("files");
            try {
                JSONCompareResult filesCompare = JSONCompare.compareJSON(cached, files,
                        JSONCompareMode.NON_EXTENSIBLE);
                if (filesCompare.passed()) {
                    complete(tempDir, files);
                    return;
                }
            } catch (JSONException e1) {
                Log.i(TAG, "Couldn't compare the file hash list with the cached file hash list: " + e1);
            }

            try {
                BufferedWriter bw = new BufferedWriter(new FileWriter(cachedFiles));
                bw.write(files.toString());
                bw.flush();
                bw.close();
            } catch (FileNotFoundException e) {
            } catch (IOException e) {
            }

            currentFile = 0;
            final int numFiles = files.length();
            Iterator<?> it = files.keys();
            while (it.hasNext()) {
                final String fileName = (String) it.next();
                final String hash = files.optString(fileName);
                final String prevHash = cached.optString(fileName);

                // If they equal, then just continue
                if (hash.equals(prevHash)) {
                    if (++currentFile == numFiles) {
                        complete(tempDir, files);
                        return;
                    }
                    continue;
                }

                // Looks like we've seen a new file, so we should reload when this is all done
                newFilesDownloaded = true;

                // Otherwise we need to download the new file
                ClutchAPIClient.downloadFile(fileName, version, new ClutchAPIDownloadResponseHandler() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            File fullFile = new File(tempDir, fileName);
                            fullFile.getParentFile().mkdirs();
                            fullFile.createNewFile();
                            BufferedWriter bw = new BufferedWriter(new FileWriter(fullFile));
                            bw.write(response);
                            bw.flush();
                            bw.close();
                        } catch (IOException e) {
                            final Writer result = new StringWriter();
                            final PrintWriter printWriter = new PrintWriter(result);
                            e.printStackTrace(printWriter);
                            Log.e(TAG, "Tried, but could not write file: " + fileName + " : " + result);
                        }

                        if (++currentFile == numFiles) {
                            complete(tempDir, files);
                            return;
                        }
                    }

                    @Override
                    public void onFailure(Throwable e, String content) {
                        final Writer result = new StringWriter();
                        final PrintWriter printWriter = new PrintWriter(result);
                        e.printStackTrace(printWriter);
                        Log.e(TAG, "Error downloading file from server: " + fileName + " " + result + " "
                                + content);
                        if (++currentFile == numFiles) {
                            complete(tempDir, files);
                            return;
                        }
                    }
                });
            }
        }

        @Override
        public void onFailure(Throwable e, JSONObject errorResponse) {
            Log.e(TAG, "Failed to sync with the Clutch server: " + errorResponse);
        }
    });
    background(clutchStats);
}

From source file:Main.java

/**
 * This method handels the reading of data from a specific file.
 * /*from   w ww  . j  a  va  2s .c o  m*/
 * @param file the file, to read from.
 * @param blockSize the length of the data-block, which should be read from the specified file.
 * @return the data read from the file.
 */
public static byte[] readFile(File file, long blockSize) {
    FileInputStream fis;
    byte[] fileContent = null;

    try {
        fis = new FileInputStream(file);

        FileChannel fileChannel = fis.getChannel();

        int bytesToRead;
        fileChannel.position(readStreamPosition);

        int dataLen = fis.available();

        // if there is a zero block size specified, read the whole file
        if (blockSize == 0L) {
            bytesToRead = dataLen;
        } else {
            bytesToRead = (int) blockSize;
        }

        fileContent = new byte[bytesToRead];

        // reading the data
        for (int i = 0; i < bytesToRead; i++) {
            fileContent[i] = (byte) fis.read();
        }

        // storing read-position
        readStreamPosition = fileChannel.position();

        fis.close();
        fileChannel.close();

        // zero blockSize indicates, that reading of this file is completed,
        // stream position reset
        if (blockSize == 0L) {
            readStreamPosition = 0L;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return fileContent;
}

From source file:net.sf.firemox.stack.EventManager.java

/**
 * remove all events in the stack of this phase, read new system abilities,
 * turn structure and set the current phase.
 * <ul>/*from  w  ww.ja va2 s .  co m*/
 * Structure of InputStream : Data[size]
 * <li>number of phases type [1]</li>
 * <li>phases type i [...]</li>
 * <li>number of phases in one turn [1]</li>
 * <li>phase identifier i [1]</li>
 * <li>phase index (not identifier) for first turn [1]</li>
 * <li>number of state based ability of play [1]</li>
 * <li>state based ability i [...]</li>
 * <li>number of static modifier of game [1]</li>
 * <li>static modifier of game i [...]</li>
 * </ul>
 * 
 * @param dbStream
 *          the MDB file containing rules
 * @param settingFile
 *          setting file attached to this MDB
 * @throws IOException
 */
public static void init(FileInputStream dbStream, String settingFile) throws IOException {
    nextCurrentPlayer = -1;
    nextPhaseIndex = -1;

    // remove all event listener
    MEventListener.reset();

    // read the different phase types
    int nbPhases = dbStream.read();
    PhaseType[] phaseTypes = new PhaseType[nbPhases];
    while (nbPhases-- > 0) {
        PhaseType phaseType = new PhaseType(dbStream);
        phaseTypes[phaseType.id] = phaseType;
    }

    // read the turn structure
    int nbPhasesPerTurn = dbStream.read();
    turnStructure = new PhaseType[nbPhasesPerTurn];
    Log.debug("Turn Structure :");
    for (int i = 0; i < nbPhasesPerTurn; i++) {
        turnStructure[i] = phaseTypes[dbStream.read()];
        Log.debug("\t" + i + ":" + turnStructure[i].phaseName);
    }

    // first phase index
    int startIdPhase = dbStream.read();
    Log.debug(
            "First phase of first turn is " + turnStructure[startIdPhase].phaseName + "(" + startIdPhase + ")");

    // read phases GUI
    try {
        final InputStream in = MToolKit.getResourceAsStream(settingFile.replace(".mdb", ".pref"));
        MPhase.phases = new MPhase[2][turnStructure.length];
        for (int i = 0; i < turnStructure.length; i++) {
            MPhase.phases[0][i] = new MPhase(turnStructure[i], 0, in);
        }
        for (int i = 0; i < EventManager.turnStructure.length; i++) {
            MPhase.phases[1][i] = new MPhase(turnStructure[i], 1, in);
        }
        IOUtils.closeQuietly(in);
    } catch (IOException e) {
        JOptionPane.showMessageDialog(MagicUIComponents.magicForm,
                LanguageManager.getString("loadtbssettingspb") + " : " + e.getMessage() + e.getStackTrace()[0],
                LanguageManager.getString("error"), JOptionPane.WARNING_MESSAGE);
    }

    // read triggered abilities of play
    int nbTriggered = dbStream.read();
    Log.debug("System abilities (" + nbTriggered + "):");
    while (nbTriggered-- > 0) {
        // read the ability and register it
        AbilityFactory.readAbility(dbStream, SystemCard.instance).registerToManager();
    }

    // reset the breakpoints, options and initialize all phases graphics
    for (int i = MPhase.phases[0].length; i-- > 1;) {
        MPhase.phases[0][i].reset();
        MPhase.phases[1][i].reset();
    }

    // set the current phase to ID__PHASE_MAIN
    phaseIndex = startIdPhase - 1;
    currentIdPhase = turnStructure[phaseIndex].id;
    parsingBeforePhaseEvent = false;
    parsingEndPhaseEvent = false;
    replacingBefore = false;

    // read static-modifiers of game
    int nbStaticModifiers = dbStream.read();
    Log.debug("Static-modifiers (" + nbStaticModifiers + "):");
    while (nbStaticModifiers-- > 0) {
        // read the static-modifiers and register them
        ModifierFactory.readModifier(dbStream).addModifierFromModel(SystemAbility.instance,
                SystemCard.instance);
    }

}

From source file:com.taobao.itemcenter.demo.utils.ItemUtils.java

public static byte[] getInputImage(String filename) {
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     FileInputStream inputFile = null;
     try {/*w w  w.  java  2  s . com*/
         inputFile = (FileInputStream) getInputStream(filename);
     } catch (FileNotFoundException e) {
         e.printStackTrace();
     }
     try {

         int b = 0;
         while ((b = inputFile.read()) != -1) {
             baos.write(b);
         }
     } catch (IOException e) {
         e.printStackTrace();
     }
     return baos.toByteArray();
 }

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.TaskUtils.java

/**
 * Loads serialized Object from disk. File can be uncompressed, gzipped or bz2-compressed.
 * Compressed files must have a .gz or .bz2 suffix.
 *
 * @param serializedFile//from   w ww.  j ava2  s  . co m
 * @return the deserialized Object
 * @throws IOException
 */
@SuppressWarnings({ "unchecked" })
public static <T> T deserialize(File serializedFile) throws IOException {
    FileInputStream fis = new FileInputStream(serializedFile);
    BufferedInputStream bufStr = new BufferedInputStream(fis);

    InputStream underlyingStream = null;
    if (serializedFile.getName().endsWith(".gz")) {
        underlyingStream = new GZIPInputStream(bufStr);
    } else if (serializedFile.getName().endsWith(".bz2")) {
        // skip bzip2 prefix that we added manually
        fis.read();
        fis.read();
        underlyingStream = new CBZip2InputStream(bufStr);
    } else {
        underlyingStream = bufStr;
    }

    ObjectInputStream deserializer = new ObjectInputStream(underlyingStream);

    Object deserializedObject = null;
    try {
        deserializedObject = deserializer.readObject();
    } catch (ClassNotFoundException e) {
        throw new IOException("The serialized file was probably corrupted.", e);
    } finally {
        deserializer.close();
    }
    return (T) deserializedObject;
}

From source file:Main.java

public void readOneByte() throws FileNotFoundException {
    FileInputStream file = null;
    byte x = -1;/* w  w w  .  j  ava 2s .c o  m*/
    try {
        file = new FileInputStream("fileName");
        x = (byte) file.read();
    } catch (FileNotFoundException f) {
        throw f;
    } catch (IOException i) {
        i.printStackTrace();
    } finally {
        try {
            if (file != null) {
                file.close();
            }
        } catch (IOException e) {
        }
    }
}

From source file:com.endgame.binarypig.util.BuildSequenceFileFromArchive.java

public void load(FileSystem fs, Configuration conf, File archive, Path outputDir) throws Exception {
    Text key = new Text();
    BytesWritable val = new BytesWritable();

    SequenceFile.Writer writer = null;
    ArchiveInputStream archiveInputStream = null;

    try {//from   ww  w .j  a  va  2  s. c  om
        Path sequenceName = new Path(outputDir, archive.getName() + ".seq");
        System.out.println("Writing to " + sequenceName);
        writer = SequenceFile.createWriter(fs, conf, sequenceName, Text.class, BytesWritable.class,
                CompressionType.RECORD);
        String lowerName = archive.toString().toLowerCase();

        if (lowerName.endsWith(".tar.gz") || lowerName.endsWith(".tgz")) {
            archiveInputStream = new ArchiveStreamFactory().createArchiveInputStream("tar",
                    new GZIPInputStream(new FileInputStream(archive)));
        } else if (lowerName.endsWith(".tar.bz") || lowerName.endsWith(".tar.bz2")
                || lowerName.endsWith(".tbz")) {
            FileInputStream is = new FileInputStream(archive);
            is.read(); // read 'B'
            is.read(); // read 'Z'
            archiveInputStream = new ArchiveStreamFactory().createArchiveInputStream("tar",
                    new CBZip2InputStream(is));
        } else if (lowerName.endsWith(".tar")) {
            archiveInputStream = new ArchiveStreamFactory().createArchiveInputStream("tar",
                    new FileInputStream(archive));
        } else if (lowerName.endsWith(".zip")) {
            archiveInputStream = new ArchiveStreamFactory().createArchiveInputStream("zip",
                    new FileInputStream(archive));
        } else {
            throw new RuntimeException("Can't handle archive format for: " + archive);
        }

        ArchiveEntry entry = null;
        while ((entry = archiveInputStream.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                try {
                    byte[] outputFile = IOUtils.toByteArray(archiveInputStream);
                    val.set(outputFile, 0, outputFile.length);
                    key.set(DigestUtils.md5Hex(outputFile));

                    writer.append(key, val);
                } catch (IOException e) {
                    System.err.println("Warning: archive may be truncated: " + archive);
                    // Truncated Archive
                    break;
                }
            }
        }
    } finally {
        archiveInputStream.close();
        writer.close();
    }
}

From source file:com.googlecode.xmlzen.utils.FileUtilsTest.java

@Test
public void testClose() throws Exception {
    FileUtils.close(null);//from   www  .  ja va2s  .co  m
    FileInputStream in = new FileInputStream(FileUtils.getClassPathFile("xmls/note.xml"));
    in.read();
    FileUtils.close(in);
    try {
        in.read();
        fail("Stream should be closed: " + in);
    } catch (final IOException e) {
        //expected
    }
    FileUtils.close(in);
    try {
        FileUtils.close(new InputStream() {
            @Override
            public int read() throws IOException {
                return 0;
            }

            @Override
            public void close() throws IOException {
                throw new IOException("Fake close exception");
            }
        });
    } catch (final RuntimeException e) {
        fail("Should be caught somewhere else");
    }
}