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:org.apache.nifi.file.FileUtils.java

/**
 * Copies the given source file to the given destination file. The given
 * destination will be overwritten if it already exists.
 *
 * @param source/*www . j a v  a 2s . c o m*/
 * @param destination
 * @param lockInputFile if true will lock input file during copy; if false
 * will not
 * @param lockOutputFile if true will lock output file during copy; if false
 * will not
 * @param move if true will perform what is effectively a move operation
 * rather than a pure copy. This allows for potentially highly efficient
 * movement of the file but if not possible this will revert to a copy then
 * delete behavior. If false, then the file is copied and the source file is
 * retained. If a true rename/move occurs then no lock is held during that
 * time.
 * @param logger if failures occur, they will be logged to this logger if
 * possible. If this logger is null, an IOException will instead be thrown,
 * indicating the problem.
 * @return long number of bytes copied
 * @throws FileNotFoundException if the source file could not be found
 * @throws IOException
 * @throws SecurityException if a security manager denies the needed file
 * operations
 */
public static long copyFile(final File source, final File destination, final boolean lockInputFile,
        final boolean lockOutputFile, final boolean move, final Logger logger)
        throws FileNotFoundException, IOException {

    FileInputStream fis = null;
    FileOutputStream fos = null;
    FileLock inLock = null;
    FileLock outLock = null;
    long fileSize = 0L;
    if (!source.canRead()) {
        throw new IOException("Must at least have read permission");

    }
    if (move && source.renameTo(destination)) {
        fileSize = destination.length();
    } else {
        try {
            fis = new FileInputStream(source);
            fos = new FileOutputStream(destination);
            final FileChannel in = fis.getChannel();
            final FileChannel out = fos.getChannel();
            if (lockInputFile) {
                inLock = in.tryLock(0, Long.MAX_VALUE, true);
                if (null == inLock) {
                    throw new IOException("Unable to obtain shared file lock for: " + source.getAbsolutePath());
                }
            }
            if (lockOutputFile) {
                outLock = out.tryLock(0, Long.MAX_VALUE, false);
                if (null == outLock) {
                    throw new IOException(
                            "Unable to obtain exclusive file lock for: " + destination.getAbsolutePath());
                }
            }
            long bytesWritten = 0;
            do {
                bytesWritten += out.transferFrom(in, bytesWritten, TRANSFER_CHUNK_SIZE_BYTES);
                fileSize = in.size();
            } while (bytesWritten < fileSize);
            out.force(false);
            FileUtils.closeQuietly(fos);
            FileUtils.closeQuietly(fis);
            fos = null;
            fis = null;
            if (move && !FileUtils.deleteFile(source, null, 5)) {
                if (logger == null) {
                    FileUtils.deleteFile(destination, null, 5);
                    throw new IOException("Could not remove file " + source.getAbsolutePath());
                } else {
                    logger.warn(
                            "Configured to delete source file when renaming/move not successful.  However, unable to delete file at: "
                                    + source.getAbsolutePath());
                }
            }
        } finally {
            FileUtils.releaseQuietly(inLock);
            FileUtils.releaseQuietly(outLock);
            FileUtils.closeQuietly(fos);
            FileUtils.closeQuietly(fis);
        }
    }
    return fileSize;
}

From source file:org.ros.internal.message.new_style.ServiceLoader.java

private void addServiceDefinitionFromPaths(File searchPath, File servicePath, CharsetDecoder decoder)
        throws IOException {
    FileInputStream inputStream = new FileInputStream(servicePath);
    FileChannel channel = inputStream.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
    channel.read(buffer);/* w ww. ja v a  2s  .  c  om*/
    buffer.rewind();
    decoder.reset();
    String definition = decoder.decode(buffer).toString().trim();
    serviceDefinitions.put(pathToServiceName(searchPath, servicePath), definition);
    channel.close();
    inputStream.close();
}

From source file:org.ros.internal.message.new_style.MessageLoader.java

private void addMessageDefinitionFromPaths(File searchPath, File messagePath, CharsetDecoder decoder)
        throws IOException {
    FileInputStream inputStream = new FileInputStream(messagePath);
    FileChannel channel = inputStream.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());
    channel.read(buffer);/*from www. jav  a  2s. com*/
    buffer.rewind();
    decoder.reset();
    String definition = decoder.decode(buffer).toString().trim();
    messageDefinitions.put(pathToMessageName(searchPath, messagePath), definition);
    channel.close();
    inputStream.close();
}

From source file:com.highcharts.export.util.SVGCreator.java

private String readFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try {/*ww w.j  a  v  a 2s .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.forName("utf-8").decode(bb).toString();
    } finally {
        stream.close();
    }
}

From source file:eu.crushedpixel.littlstar.api.upload.S3Uploader.java

/**
 * Executes a multipart form upload to the S3 Bucket as described in
 * <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTExamples.html">the AWS Documentation</a>.
 * @param s3UploadProgressListener An S3UploadProgressListener which is called whenever
 *                               bytes are written to the outgoing connection. May be null.
 * @throws IOException in case of a problem or the connection was aborted
 * @throws ClientProtocolException in case of an http protocol error
 *///from   w ww . j  av a  2s .c  o m
public void uploadFileToS3(S3UploadProgressListener s3UploadProgressListener)
        throws IOException, ClientProtocolException {
    //unfortunately, we can't use Unirest to execute the call, because there is no support
    //for Progress listeners (yet). See https://github.com/Mashape/unirest-java/issues/26

    int bufferSize = 1024;

    //opening a connection to the S3 Bucket
    HttpURLConnection urlConnection = (HttpURLConnection) new URL(s3_bucket).openConnection();
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setChunkedStreamingMode(bufferSize);
    urlConnection.setRequestProperty("Connection", "Keep-Alive");
    urlConnection.setRequestProperty("Cache-Control", "no-cache");
    String boundary = "*****";
    urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    //writing the request headers
    DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());

    String newline = "\r\n";
    String twoHyphens = "--";
    dos.writeBytes(twoHyphens + boundary + newline);

    String attachmentName = "file";
    String attachmentFileName = "file";

    dos.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\""
            + attachmentFileName + "\"" + newline);
    dos.writeBytes(newline);

    //sending the actual file
    byte[] buf = new byte[bufferSize];

    FileInputStream fis = new FileInputStream(file);
    long totalBytes = fis.getChannel().size();
    long writtenBytes = 0;

    int len;
    while ((len = fis.read(buf)) != -1) {
        dos.write(buf);
        writtenBytes += len;

        s3UploadProgressListener.onProgressUpdated(new S3UpdateProgressEvent(writtenBytes, totalBytes,
                (float) ((double) writtenBytes / totalBytes)));

        if (interrupt) {
            fis.close();
            dos.close();
            return;
        }
    }

    fis.close();

    //finish the call
    dos.writeBytes(newline);
    dos.writeBytes(twoHyphens + boundary + twoHyphens + newline);

    dos.close();

    urlConnection.disconnect();
}

From source file:org.talend.studio.StudioInstaller.java

boolean checkFile(File file, String data) {
    FileInputStream fis = null;
    try {//from w  ww.j ava  2s  .c om
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        fis = new FileInputStream(file);
        FileChannel fc = fis.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            int length = fc.read(buffer);
            if (length < 1) {
                break;
            }
            buffer.flip();
            md5.update(buffer);
            buffer.clear();
        }
        byte[] ret = md5.digest();
        return BuildUtil.toHexString(ret).equals(data.trim().toUpperCase());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fis);
    }
    return false;
}

From source file:com.almunt.jgcaap.systemupdater.DownloadService.java

public void copy(File src, File dst) throws IOException {
    FileInputStream inStream = new FileInputStream(src);
    FileOutputStream outStream = new FileOutputStream(dst);
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    inStream.close();// w w w . j a va2  s .  c  om
    outStream.close();
}

From source file:com.l2jfree.loginserver.L2LoginIdentifier.java

private synchronized void load() {
    if (isLoaded())
        return;/*  w ww  . j  av a  2 s .  co m*/

    File f = new File(System.getProperty("user.home", null), FILENAME);
    ByteBuffer bb = ByteBuffer.allocateDirect(8);

    if (!f.exists() || f.length() != 8) {
        _uid = getRandomUID();
        _loaded = true;
        _log.info("A new UID has been generated for this login server.");

        FileOutputStream fos = null;
        try {
            f.createNewFile();
            fos = new FileOutputStream(f);
            FileChannel fc = fos.getChannel();
            bb.putLong(getUID());
            bb.flip();
            fc.write(bb);
            fos.flush();
        } catch (IOException e) {
            _log.warn("Could not store login server's UID!", e);
        } finally {
            IOUtils.closeQuietly(fos);
            f.setReadOnly();
        }
    } else {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f);
            FileChannel fc = fis.getChannel();
            fc.read(bb);
        } catch (IOException e) {
            _log.warn("Could not read stored login server's UID!", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }

        if (bb.position() > 0) {
            bb.flip();
            _uid = bb.getLong();
        } else
            _uid = getRandomUID();
        _loaded = true;
    }
}

From source file:edu.rit.flick.genetics.FastqFileInflator.java

@Override
protected void createOutputFiles(final String tempOutputDirectory, final File fastFile) throws IOException {
    super.createOutputFiles(tempOutputDirectory, fastFile);

    lengthfile = new BufferedInputStream(
            new FileInputStream(getFile(tempOutputDirectory, SEQUENCE_LENGTH_FILE)), DEFAULT_BUFFER) {
        @Override/*from  w w w.j a  va2s .  c  om*/
        public synchronized int read() throws IOException {
            return super.read() << 8 | super.read() & 0x00ff;
        }
    };
    commentsfile = new Scanner(getFile(tempOutputDirectory, COMMENTS_FILE));

    final FileInputStream scoreFis = new FileInputStream(getFile(tempOutputDirectory, SEQUENCE_SCORE_FILE));
    scorefile = ByteBufferInputStream.map(scoreFis.getChannel());

    scoreFis.close();
}

From source file:org.kevinferrare.solarSystemDataRetriever.jplhorizons.webfetcher.JplHorizonRawDataRetriever.java

/**
 * Loads data from the folder that was set using setFolderName.<br />
 * The loaded keys are the file names and the associated value is the file content.
 * //  www  . j  ava  2  s. c  o m
 * @return a Map with the data loaded from the folder
 * @throws IOException
 */
public Map<String, String> loadFromFolder() throws IOException {
    Map<String, String> rawDataMap = new HashMap<String, String>();
    File folder = new File(folderName);
    if (!folder.exists()) {
        log.error("Invalid folder " + folderName);
        return null;
    }
    File[] listOfFiles = folder.listFiles(new OnlyExtensionFilter(RAW_DATA_FILE_EXTENSION));
    for (File file : listOfFiles) {
        String name = file.getName().replace("." + RAW_DATA_FILE_EXTENSION, "");
        FileInputStream stream = new FileInputStream(file);
        FileChannel fileChannel = stream.getChannel();
        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0,
                fileChannel.size());
        String content = Charset.forName("ASCII").decode(mappedByteBuffer).toString();
        stream.close();
        rawDataMap.put(name, content);
    }
    return rawDataMap;
}