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:com.wipro.sa349342.wmar.AbstractArchitectCamActivity.java

public void createFCListFromJsonFile() {
    try {/*from   w ww.  j  ava2 s.  co  m*/

        //downloadAndStoreJson("http://jsonblob.com/api/jsonBlob/57b57cc1e4b0dc55a4edf932");

        File jsonFile = new File(Environment.getExternalStorageDirectory().getPath(),
                MainActivityLanding.DefaultJSONFileFromMemeory);
        /*if (!jsonFile.isFile()) {
        System.out.println("MyGlobalVariables--readJSONFromMemory::-downloaded json file not found.Switching to default file");
        jsonFile = new File(Environment.getExternalStorageDirectory().getPath(), MyGlobalVariables.defaultJSONFileFromMemeory);
                
        }*/

        FileInputStream stream = new FileInputStream(jsonFile);
        String jsonStr = null;

        try {
            FileChannel fc = stream.getChannel();
            MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());

            jsonStr = Charset.defaultCharset().decode(bb).toString();
        } finally {
            stream.close();
        }

        JSONObject jsonObj = new JSONObject(jsonStr);

        // Getting data JSON Array nodes
        // JSONArray data = jsonObj.getJSONArray("utility_lines");

        addFeaturesInList(jsonObj.getJSONArray("utility_lines"), UtlityLinesFeatureList, "utility_lines");
        addFeaturesInList(jsonObj.getJSONArray("equipments"), EquipmentsFeatureList, "equipments");

        com.google.android.gms.maps.model.CameraPosition cameraPosition = new com.google.android.gms.maps.model.CameraPosition.Builder()
                .target(new LatLng(12.8363773, 77.6585139))
                //.target(london_eye)//Sets the center of the map to
                .zoom(19) // Sets the zoom
                .bearing(0) // Sets the orientation of the camera to east
                .tilt(0) // Sets the tilt of the camera to 1 degrees
                .build();

        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

private void copyWaveFile(String inFilename, String outFilename) {
    FileInputStream in = null;
    FileOutputStream out = null;//from ww w .j ava2 s .  c  o  m
    long totalAudioLen = 0;
    long totalDataLen = totalAudioLen + 36;
    long longSampleRate = RECORDER_SAMPLERATE;
    int channels = 1;
    long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels / 8;

    int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS,
            RECORDER_AUDIO_ENCODING);
    byte[] data = new byte[bufferSize];

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

        Log.w("PlayAllAudioAction", "File size: " + totalDataLen);

        WriteWaveFileHeader(out, totalAudioLen, totalDataLen, longSampleRate, 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:com.ferdi2005.secondgram.AndroidUtilities.java

public static boolean copyFile(File sourceFile, File destFile) throws IOException {
    if (!destFile.exists()) {
        destFile.createNewFile();/*from   www.  j a v a2  s .c  o  m*/
    }
    FileInputStream source = null;
    FileOutputStream destination = null;
    try {
        source = new FileInputStream(sourceFile);
        destination = new FileOutputStream(destFile);
        destination.getChannel().transferFrom(source.getChannel(), 0, source.getChannel().size());
    } catch (Exception e) {
        FileLog.e(e);
        return false;
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
    return true;
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.PBImageTextWriter.java

/** Load the directories in the INode section. */
private void loadDirectories(FileInputStream fin, List<FileSummary.Section> sections, FileSummary summary,
        Configuration conf) throws IOException {
    LOG.info("Loading directories");
    long startTime = Time.monotonicNow();
    for (FileSummary.Section section : sections) {
        if (SectionName.fromString(section.getName()) == SectionName.INODE) {
            fin.getChannel().position(section.getOffset());
            InputStream is = FSImageUtil.wrapInputStreamForCompression(conf, summary.getCodec(),
                    new BufferedInputStream(new LimitInputStream(fin, section.getLength())));
            loadDirectoriesInINodeSection(is);
        }/*from w  w  w .  ja va 2 s . c  o  m*/
    }
    long timeTaken = Time.monotonicNow() - startTime;
    LOG.info("Finished loading directories in {}ms", timeTaken);
}

From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

public void copyObject(String sourceBucket, String sourceObject, String destinationBucket,
        String destinationObject) throws IOException {
    File oldObjectFile = new File(
            rootDirectory + FILE_SEPARATOR + sourceBucket + FILE_SEPARATOR + sourceObject);
    File newObjectFile = new File(
            rootDirectory + FILE_SEPARATOR + destinationBucket + FILE_SEPARATOR + destinationObject);
    if (!oldObjectFile.equals(newObjectFile)) {
        FileInputStream fileInputStream = null;
        FileChannel fileIn = null;
        FileOutputStream fileOutputStream = null;
        FileChannel fileOut = null;
        try {/*from w  ww  .  j a  va  2s.  c  o  m*/
            fileInputStream = new FileInputStream(oldObjectFile);
            fileIn = fileInputStream.getChannel();
            fileOutputStream = new FileOutputStream(newObjectFile);
            fileOut = fileOutputStream.getChannel();
            fileIn.transferTo(0, fileIn.size(), fileOut);
        } finally {
            if (fileIn != null)
                fileIn.close();
            if (fileInputStream != null)
                fileInputStream.close();
            if (fileOut != null)
                fileOut.close();
            if (fileOutputStream != null)
                fileOutputStream.close();
        }
    }
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.PBImageTextWriter.java

private void loadINodeDirSection(FileInputStream fin, List<FileSummary.Section> sections, FileSummary summary,
        Configuration conf) throws IOException {
    LOG.info("Loading INode directory section.");
    long startTime = Time.monotonicNow();
    for (FileSummary.Section section : sections) {
        if (SectionName.fromString(section.getName()) == SectionName.INODE_DIR) {
            fin.getChannel().position(section.getOffset());
            InputStream is = FSImageUtil.wrapInputStreamForCompression(conf, summary.getCodec(),
                    new BufferedInputStream(new LimitInputStream(fin, section.getLength())));
            buildNamespace(is);/*from  w w  w . j a  va2 s  . c om*/
        }
    }
    long timeTaken = Time.monotonicNow() - startTime;
    LOG.info("Finished loading INode directory section in {}ms", timeTaken);
}

From source file:hd3gtv.mydmam.useraction.fileoperation.CopyMove.java

private void copyFile(File source_file, File destination_file) throws IOException {
    if (destination_file.exists()) {
        Log2Dump dump = new Log2Dump();
        dump.add("source_file", source_file);
        dump.add("destination_file", destination_file);
        dump.add("delete_after_copy", delete_after_copy);

        if (fileexistspolicy == FileExistsPolicy.IGNORE) {
            Log2.log.debug("Destination file exists, ignore copy/move", dump);
            return;
        } else if (fileexistspolicy == FileExistsPolicy.OVERWRITE) {
            Log2.log.debug("Destination file exists, overwrite it", dump);
            FileUtils.forceDelete(destination_file);
        } else if (fileexistspolicy == FileExistsPolicy.RENAME) {
            // destination_file
            int cursor = 1;
            int dot_pos;
            StringBuilder sb;/*w  ww.ja v  a  2 s .  co m*/
            while (destination_file.exists()) {
                sb = new StringBuilder();
                sb.append(destination_file.getParent());
                sb.append(File.separator);
                dot_pos = destination_file.getName().lastIndexOf(".");
                if (dot_pos > 0) {
                    sb.append(destination_file.getName().substring(0, dot_pos));
                    sb.append(" (");
                    sb.append(cursor);
                    sb.append(")");
                    sb.append(
                            destination_file.getName().substring(dot_pos, destination_file.getName().length()));
                } else {
                    sb.append(destination_file.getName());
                    sb.append(" (");
                    sb.append(cursor);
                    sb.append(")");
                }
                destination_file = new File(sb.toString());
                cursor++;
            }
            dump.add("new destination file name", destination_file);
            Log2.log.debug("Destination file exists, change destionation name", dump);
        }
    }
    /**
     * Imported from org.apache.commons.io.FileUtils
     * Licensed to the Apache Software Foundation,
     * http://www.apache.org/licenses/LICENSE-2.0
     */
    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileChannel input = null;
    FileChannel output = null;
    try {
        fis = new FileInputStream(source_file);
        fos = new FileOutputStream(destination_file);
        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);

            if (progression != null) {
                actual_progress_value = (int) ((pos + progress_copy) / (1024 * 1024));
                if (actual_progress_value > last_progress_value) {
                    last_progress_value = actual_progress_value;
                    progression.updateProgress(actual_progress_value, progress_size);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(output);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fis);
    }

    if (source_file.length() != destination_file.length()) {
        throw new IOException(
                "Failed to copy full contents from '" + source_file + "' to '" + destination_file + "'");
    }
    if (destination_file.setExecutable(source_file.canExecute()) == false) {
        Log2.log.error("Can't set Executable status to dest file", new IOException(destination_file.getPath()));
    }
    if (destination_file.setLastModified(source_file.lastModified()) == false) {
        Log2.log.error("Can't set LastModified status to dest file",
                new IOException(destination_file.getPath()));
    }
}

From source file:org.cloudata.core.commitlog.CommitLogServer.java

public int readLastLogFromMarkedPosition(String dirName) {
    File logFile = getLogFile(dirName);
    File indexFile = getLogIndexFile(dirName);

    FileChannel ch = null;//from  ww  w .  j  a v  a 2s .  c  o  m
    try {
        long index = 0;

        if (logFile.exists() == false) {
            LOG.warn("A directory [" + dirName + "] or log file does not exist");
            return -1;
        } else if (indexFile.exists()) {
            FileChannel indexChannel = new FileInputStream(indexFile).getChannel();
            index = CommitLogFileChannel.readLastIndex(indexChannel);
            LOG.info("index of dir [" + dirName + "] : " + index);
            indexChannel.close();
        }

        FileInputStream in = new FileInputStream(logFile);
        ch = in.getChannel();
        ch.position(index);
    } catch (IOException e) {
        LOG.error("Fail to read logs", e);
        return -1;
    }

    return startFileTransferChannel(dirName, ch);
}

From source file:com.fratello.longevity.smooth.AppGUI.java

private void generateList() throws IOException {
    MasterList.clear();//from  w  ww. jav a2  s  .c om
    SentinelProgressLabel.setText("Gathering files in directory");
    Collection<File> toConvert = new ArrayList<File>();
    for (String sDir : StartingDirectories) {
        toConvert.addAll(FileUtils.listFiles(new File(sDir), null, true));
    }
    SentinelProgressLabel.setText("Collecting file data");
    SentinelProgressBar.setMaximum(toConvert.size());
    int counter = 0;
    LabelMaxSize = MasterList.size();
    for (File sfFile : toConvert) {
        FileInputStream fis = new FileInputStream(sfFile);
        int fileSizeFromFIS = (int) fis.getChannel().size();
        SpecialFile sfConverted = null;
        if (cf.getUse("Thorough")) {
            sfConverted = new SpecialFile(Arrays.asList(ArrayUtils.toObject(IOUtils.toByteArray(fis))),
                    fileSizeFromFIS, Paths.get(sfFile.getPath()));
        } else {
            sfConverted = new SpecialFile(fileSizeFromFIS, Paths.get(sfFile.getPath()));
        }
        MasterList.add(sfConverted);
        publish(++counter);
        fis.close();
        if (GUI_Stop || GUI_Pause) {
            GUI_Pause = true;
            if (GUI_Stop) {
                clearFields();
                GUI_Stop = false;
            }
            GUI_Start = false;
            break;
        }
    }
    if (deleteCopyResults) {
        delStuff();
    } else if (saveCopyResults) {
        saveDuplicateResults();
    } else if (saveCopyResults && deleteCopyResults) {
        saveDuplicateResults();
        delStuff();
    }
    GUI_Start = false;
    GUI_Pause = true;
}

From source file:in.neoandroid.neoupdate.neoUpdate.java

private boolean downloadFile(NewAsset asset, String toPath, TarArchiveInputStream tin, TarArchiveEntry ae) {
    if (enableDebug)
        Log.d(TAG, "Start download: " + asset.path + ":NPK: " + (tin != null));
    boolean resume = (db.updateAndGetStatus(asset.path, asset.md5) == neoUpdateDB.UPDATE_STATUS.UPDATE_RESUME);
    String newPath;/*from ww  w  .ja va 2  s . c om*/
    if (toPath != null)
        newPath = toPath;
    else
        newPath = mapPath(asset.path);
    createSubDirectories(newPath);
    File newFile = new File(newPath);
    long fromBytes = 0;
    if (resume)
        fromBytes = newFile.length();

    try {
        FileOutputStream os = new FileOutputStream(newFile, resume);
        db.setMd5(asset.path, asset.md5);

        if (tin != null && ae != null) {
            // Via NPK
            final int BUFF_SIZE = (8 * 1024); // Buffer size of 8KB
            byte[] buffer = new byte[BUFF_SIZE];
            int n = 0;
            long size = ae.getSize();
            if (resume && fromBytes > 0 && fromBytes < size) {
                tin.skip(fromBytes);
                size -= fromBytes;
            }
            while (size > 0) {
                n = BUFF_SIZE;
                if (n > size)
                    n = (int) size;
                n = tin.read(buffer, 0, n);
                if (n < 0)
                    break;
                if (n > 0)
                    os.write(buffer, 0, n);
            }
        } else if (nConnections <= 0) {
            // Via Local File System
            FileInputStream is = new FileInputStream(baseUrl + asset.path);
            is.getChannel().transferTo(fromBytes, is.getChannel().size() - fromBytes, os.getChannel());
            is.close();
        } else {
            // Via Internet
            HttpResponse resp = HttpWithPostData(asset.path, fromBytes);
            resp.getEntity().writeTo(os);
        }
        db.setDownloaded(asset.path, true);
        os.close();
    } catch (Exception e) {
        if (enableDebug)
            e.printStackTrace();
        return false;
    }
    return true;
}