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:thv.th.reader.SavegameReader.java

public static THMap read(FileInputStream frameStream, FileInputStream frameListStream,
        FileInputStream frameElementStream, File frameTabFile, File frameChunksFile, THPalette framePalette,
        FileInputStream saveStream, ABuffer blockTabStream, FileInputStream blockChunkStream,
        THPalette blockPalette, Color background) throws IOException {
    Vector<BufferedImage> tiles = ChunksReader.readAll(blockChunkStream, blockTabStream, blockPalette,
            background);/*from w  ww. j  a  va  2s  . co m*/
    THMap result = new THMap();

    saveStream.getChannel().position(13);

    for (int y = 0; y < 128; ++y) {
        for (int x = 0; x < 128; ++x) {
            int pos = (int) saveStream.getChannel().position() + 21;
            int anim = EndianUtils.readSwappedShort(saveStream);

            int layer0id = saveStream.read();
            int layer1id = saveStream.read();
            int layer2id = saveStream.read();

            layer0id = LevelReader.tileMap[layer0id];
            layer1id = LevelReader.tileMap[layer1id];
            layer2id = LevelReader.tileMap[layer2id];

            BufferedImage l0 = tiles.elementAt(layer0id);
            BufferedImage l1 = null;
            BufferedImage l2 = null;
            if (layer1id > 0) {
                l1 = tiles.elementAt(layer1id);
            }

            if (layer2id > 0) {
                l2 = tiles.elementAt(layer2id);
            }

            saveStream.skip(1);
            int extra = saveStream.read();
            saveStream.skip(1);

            Tile tile = new Tile(anim, l0, l1, l2, pos);

            switch (extra >>> 4) {
            case 2:
            case 10:
                tile.setShadow1(tiles.get(154));
                break;
            case 3:
            case 11:
                tile.setShadow0(tiles.get(74));
                tile.setShadow1(tiles.get(154));
                break;
            case 6:
            case 7:
            case 14:
            case 15:
                tile.setShadow0(tiles.get(73));
                tile.setShadow1(tiles.get(154));
                break;
            case 1:
            case 9:
                tile.setShadow0(tiles.get(74));
                break;
            case 4:
            case 5:
            case 12:
            case 13:
                tile.setShadow0(tiles.get(73));
                break;

            }

            switch (extra & 0xf) {
            case 1:
                tile.setLitter(FramesReader.readByIndex(3737, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 2:
                tile.setLitter(FramesReader.readByIndex(3738, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 3:
                tile.setLitter(FramesReader.readByIndex(3739, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 4:
                tile.setLitter(FramesReader.readByIndex(4533, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 5:
                tile.setLitter(FramesReader.readByIndex(3741, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 6:
                tile.setLitter(FramesReader.readByIndex(4542, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            case 7:
                tile.setLitter(FramesReader.readByIndex(3742, frameStream, frameListStream, frameElementStream,
                        frameTabFile, frameChunksFile, framePalette));
                break;
            }

            long nextPos = saveStream.getChannel().position();

            readObjectInfo(saveStream, tile, frameStream, frameListStream, frameElementStream, frameTabFile,
                    frameChunksFile, framePalette);
            result.setTile(x, y, tile);

            saveStream.getChannel().position(nextPos);
        }
    }

    /*for(int y = 0; y < 128; ++y) {
    for(int x = 0; x < 128; ++x) {
        int pid = EndianUtils.readSwappedShort(mapStream);
                
        result.getTile(x, y).setParcel(pid);
    }
    }*/

    saveStream.close();
    return result;
}

From source file:net.darkmist.alib.io.BufferUtil.java

public static ByteBuffer mapOrSlurp(File file) throws IOException {
    FileInputStream fin = null;
    FileChannel fc = null;/*from   ww  w.  j a va2 s.c  om*/

    try {
        fin = new FileInputStream(file);
        try {
            fc = fin.getChannel();
            return fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
        } catch (IOException e) {
            logger.debug("Ignoring IOException caught trying to map file {}", file, e);
        }
        return asBuffer(fin);
    } finally {
        fc = Closer.close(fc);
        fin = Closer.close(fin);
    }
}

From source file:com.github.fritaly.dualcommander.Utils.java

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");
    }/* w  ww  .  ja  v a  2  s.com*/

    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 > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
            pos += output.transferFrom(input, pos, count);
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.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());
    }
}

From source file:password.pwm.util.secure.SecureEngine.java

public static String hash(final File file, final PwmHashAlgorithm hashAlgorithm)
        throws IOException, PwmUnrecoverableException {
    FileInputStream fileInputStream = null;
    try {// w  w w. j av  a 2  s  . co  m
        final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgName());
        fileInputStream = new FileInputStream(file);
        final FileChannel fileChannel = fileInputStream.getChannel();
        final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024 * 8);

        while (fileChannel.read(byteBuffer) > 0) {
            byteBuffer.flip();
            messageDigest.update(byteBuffer);
            byteBuffer.clear();
        }

        return JavaHelper.byteArrayToHexString(messageDigest.digest());

    } catch (NoSuchAlgorithmException | IOException e) {
        final String errorMsg = "unexpected error during file hash operation: " + e.getMessage();
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, errorMsg);
        throw new PwmUnrecoverableException(errorInformation);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:at.treedb.jslib.JsLib.java

/**
 * Loads an external JavaScript library.
 * //from ww  w  . ja v  a 2s .  co m
 * @param dao
 *            {@code DAOiface} (data access object)
 * @param name
 *            library name
 * @param version
 *            optional library version. If this parameter is null the
 *            library with the highest version number will be loaded
 * @return {@code JsLib} object
 * @throws Exception
 */
@SuppressWarnings("resource")
public static synchronized JsLib load(DAOiface dao, String name, String version) throws Exception {
    initJsLib(dao);
    if (jsLibs == null) {
        return null;
    }
    JsLib lib = null;
    synchronized (lockObj) {
        HashMap<Version, JsLib> v = jsLibs.get(name);
        if (v == null) {
            return null;
        }

        if (version != null) {
            lib = v.get(new Version(version));
        } else {
            Version[] array = v.keySet().toArray(new Version[v.size()]);
            Arrays.sort(array);
            // return the library with the highest version number
            lib = v.get(array[array.length - 1]);
        }
    }
    if (lib != null) {
        if (!lib.isExtracted) {
            // load binary archive data
            lib.callbackAfterLoad(dao);
            // detect zip of 7z archive
            MimeType mtype = ContentInfo.getContentInfo(lib.data);
            int totalSize = 0;
            HashMap<String, byte[]> dataMap = null;
            String libName = "jsLib" + lib.getHistId();
            String classPath = lib.getName() + "/java/classes/";
            if (mtype != null) {
                // ZIP archive
                if (mtype.equals(MimeType.ZIP)) {
                    dataMap = new HashMap<String, byte[]>();
                    lib.zipInput = new ZipArchiveInputStream(new ByteArrayInputStream(lib.data));
                    do {
                        ZipArchiveEntry entry = lib.zipInput.getNextZipEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.zipInput.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }
                    } while (true);
                    lib.zipInput.close();
                    lib.isExtracted = true;
                    // 7-zip archive
                } else if (mtype.equals(MimeType._7Z)) {
                    dataMap = new HashMap<String, byte[]>();
                    File tempFile = FileStorage.getInstance().createTempFile(libName, ".7z");
                    tempFile.deleteOnExit();
                    Stream.writeByteStream(tempFile, lib.data);
                    lib.sevenZFile = new SevenZFile(tempFile);
                    do {
                        SevenZArchiveEntry entry = lib.sevenZFile.getNextEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.sevenZFile.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }

                    } while (true);
                    lib.sevenZFile.close();
                    lib.isExtracted = true;
                }
            }
            if (!lib.isExtracted) {
                throw new Exception("JsLib.load(): No JavaScript archive extracted!");
            }
            // create a buffer for the archive
            byte[] buf = new byte[totalSize];
            int offset = 0;
            // enumerate the archive entries
            for (String n : dataMap.keySet()) {
                byte[] d = dataMap.get(n);
                System.arraycopy(d, 0, buf, offset, d.length);
                lib.archiveMap.put(n, new ArchiveEntry(offset, d.length));
                offset += d.length;
            }
            // create a temporary file containing the extracted archive
            File tempFile = FileStorage.getInstance().createTempFile(libName, ".dump");
            lib.dumpFile = tempFile;
            tempFile.deleteOnExit();
            Stream.writeByteStream(tempFile, buf);
            FileInputStream inFile = new FileInputStream(tempFile);
            // closed by the GC
            lib.inChannel = inFile.getChannel();
            // discard the archive data - free the memory
            lib.data = null;
            dataMap = null;
        }
    }
    return lib;
}

From source file:org.sakaiproject.emailtemplateservice.service.impl.EmailTemplateServiceImpl.java

private static String readFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try {/*from  ww  w .  jav  a2  s .  c o m*/
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        /* Instead of using default, pass in a decoder. */
        return Charset.defaultCharset().decode(bb).toString();
    } finally {
        stream.close();
    }
}

From source file:me.carpela.network.pt.cracker.tools.ttorrent.Torrent.java

private static String hashFiles(List<File> files, int pieceLenght)
        throws InterruptedException, IOException, NoSuchAlgorithmException {
    int threads = getHashingThreadsCount();
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    ByteBuffer buffer = ByteBuffer.allocate(pieceLenght);
    List<Future<String>> results = new LinkedList<Future<String>>();
    StringBuilder hashes = new StringBuilder();

    long length = 0L;
    int pieces = 0;

    long start = System.nanoTime();
    for (File file : files) {

        length += file.length();/*  w w w.  ja  v  a  2  s  .c o m*/

        FileInputStream fis = new FileInputStream(file);
        FileChannel channel = fis.getChannel();
        int step = 10;

        try {
            while (channel.read(buffer) > 0) {
                if (buffer.remaining() == 0) {
                    buffer.clear();
                    results.add(executor.submit(new CallableChunkHasher(buffer)));
                }

                if (results.size() >= threads) {
                    pieces += accumulateHashes(hashes, results);
                }

                if (channel.position() / (double) channel.size() * 100f > step) {
                    step += 10;
                }
            }
        } finally {
            channel.close();
            fis.close();
        }
    }

    // Hash the last bit, if any
    if (buffer.position() > 0) {
        buffer.limit(buffer.position());
        buffer.position(0);
        results.add(executor.submit(new CallableChunkHasher(buffer)));
    }

    pieces += accumulateHashes(hashes, results);

    // Request orderly executor shutdown and wait for hashing tasks to
    // complete.
    executor.shutdown();
    while (!executor.isTerminated()) {
        Thread.sleep(10);
    }
    long elapsed = System.nanoTime() - start;

    int expectedPieces = (int) (Math.ceil((double) length / pieceLenght));
    return hashes.toString();
}

From source file:cd.education.data.collector.android.utilities.FileUtils.java

private static String actualCopy(File sourceFile, File destFile) {
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    FileChannel src = null;//from  w  w w. ja  va2s  .co  m
    FileChannel dst = null;
    try {
        fileInputStream = new FileInputStream(sourceFile);
        src = fileInputStream.getChannel();
        fileOutputStream = new FileOutputStream(destFile);
        dst = fileOutputStream.getChannel();
        dst.transferFrom(src, 0, src.size());
        dst.force(true);
        return null;
    } catch (FileNotFoundException e) {
        Log.e(t, "FileNotFoundException while copying file", e);
        return e.getMessage();
    } catch (IOException e) {
        Log.e(t, "IOException while copying file", e);
        return e.getMessage();
    } catch (Exception e) {
        Log.e(t, "Exception while copying file", e);
        return e.getMessage();
    } finally {
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(fileOutputStream);
        IOUtils.closeQuietly(src);
        IOUtils.closeQuietly(dst);
    }
}

From source file:org.apache.hadoop.hdfs.shortcircuit.ShortCircuitShm.java

/**
 * Calculate the usable size of a shared memory segment.
 * We round down to a multiple of the slot size and do some validation.
 *
 * @param stream The stream we're using.
 * @return       The usable size of the shared memory segment.
 *///w  w w . ja  v a 2s  .c om
private static int getUsableLength(FileInputStream stream) throws IOException {
    int intSize = Ints.checkedCast(stream.getChannel().size());
    int slots = intSize / BYTES_PER_SLOT;
    if (slots == 0) {
        throw new IOException("size of shared memory segment was " + intSize
                + ", but that is not enough to hold even one slot.");
    }
    return slots * BYTES_PER_SLOT;
}

From source file:gov.nasa.ensemble.common.io.FileUtilities.java

/**
 * Make a copy of a file on the filesystem (platform independent).
 * //  w w w .  j a  v  a  2s.  c o  m
 * @param source
 *            the file to copy.
 * @param dest
 *            the copy to make.
 * @return whether the file copy exists on the filesystem upon completion.
 * @throws IOException
 */
public static boolean copyFile(File source, File dest) throws IOException {
    FileInputStream sourceStream = new FileInputStream(source);
    FileChannel sourceChannel = sourceStream.getChannel();
    FileOutputStream destStream = new FileOutputStream(dest);
    FileChannel destChannel = destStream.getChannel();
    try {
        sourceChannel.transferTo(0, sourceChannel.size(), destChannel);
    } catch (IOException ex) {
        if (ex.getCause() instanceof OutOfMemoryError) {
            IOUtils.copy(sourceStream, destStream);
        }
    } finally {
        destChannel.close();
        IOUtils.closeQuietly(destStream);
        sourceChannel.close();
        IOUtils.closeQuietly(sourceStream);
    }

    return dest.exists();
}