Example usage for java.nio.channels FileChannel close

List of usage examples for java.nio.channels FileChannel close

Introduction

In this page you can find the example usage for java.nio.channels FileChannel close.

Prototype

public final void close() throws IOException 

Source Link

Document

Closes this channel.

Usage

From source file:com.slytechs.capture.file.editor.FileEditorImpl.java

/**
 * <p>//from w  w w . j  a v  a  2  s  . co  m
 * Flushes all the changes that currently exist in the "edits" buffer into a
 * temporary secondary file. After the copy the original file is removed and
 * the temporary file is renamed back to the original file which now contains
 * the contents of the "edits" buffer.
 * </p>
 * <p>
 * All the regions and their overlays are iterated over one segment at a time,
 * this includes the big segment consiting of the original file content, and
 * their reader's are asked to copy their buffers out to the temporary file's
 * channel in their individual smaller segments.
 * </p>
 * 
 * @throws IOException
 *           any IO errors with either the source file or the temporary file
 *           operation's during the flush
 */
private void flushByCopy() throws IOException {

    /*
     * Create a temp file
     */

    final File temp = File.createTempFile(this.file.getName(), null);

    final FileChannel tempChannel = new RandomAccessFile(temp, "rw").getChannel();

    /*
     * Copy entire edits tree, including the root file, to temp file
     */
    for (final RegionSegment<PartialLoader> segment : this.edits) {
        final PartialLoader loader = new ConstrainedPartialLoader(segment.getData(), segment);

        loader.transferTo(tempChannel);
    }
    this.channel.close();
    tempChannel.close();

    System.gc();

    /*
     * We're done with the original file. All changes are now in the temp file
     * Try rename first, if it doesn't exist then do it by copy
     */
    if (file.delete() == false) {
        throw new IOException("Unable to delete original file during flushByCopy()");
    }
    if (temp.renameTo(file) == false) {
        throw new IOException("Unable to move temporary file during flushByCopy()");
    }

    final String accessMode = (mode.isContent() ? "rw" : "r");

    /*
     * Now we need to reopen the channel
     */
    this.channel = new RandomAccessFile(file, accessMode).getChannel();
}

From source file:org.gephi.ui.components.ReportSelection.java

public void copy(File source, File dest) throws IOException {
    FileChannel in = null, out = null;
    try {//from  w  ww  .ja  v a  2s. c om
        if (dest.isDirectory()) {
            dest = new File(dest, source.getName());
        }
        in = new FileInputStream(source).getChannel();
        out = new FileOutputStream(dest).getChannel();

        long size = in.size();
        MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);

        out.write(buf);

    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.warfrog.bitmapallthethings.BattEngine.java

private void decodeBitmap(String filename) throws IOException {
    System.out.println("Decoding " + filename);

    File inputFile = new File(filename);
    File outputFile = new File(
            outputDirectory + File.separator + FilenameUtils.removeExtension(inputFile.getName()));

    FileInputStream fis = new FileInputStream(filename);
    //skip 6 bytes
    fis.skip(6);//w w  w . j av  a2s .co m
    //read the length we encoded
    int fileSize = EndianUtils.readSwappedInteger(fis);
    //skip the rest of the header
    fis.skip(44);
    Files.copy(fis, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    //truncate the file
    FileChannel outChan = new FileOutputStream(outputFile, true).getChannel();
    outChan.truncate(fileSize);
    outChan.close();

    //clean up
    if (isCleanUp()) {
        //delete the bitmap
        System.out.println("Deleting: " + inputFile);
        FileUtils.deleteQuietly(inputFile);
    }
}

From source file:org.apache.hadoop.yarn.server.security.CertificateLocalizationService.java

private void writeX509ToLocalFS(ByteBuffer keyStore, File keyStoreLocation, ByteBuffer trustStore,
        File trustStoreLocation, String password, File passwordFileLocation) throws IOException {
    FileChannel keyStoreChannel = new FileOutputStream(keyStoreLocation, false).getChannel();
    keyStoreChannel.write(keyStore);//w  w w. java 2 s  .  c  om
    keyStoreChannel.close();

    FileChannel trustStoreChannel = new FileOutputStream(trustStoreLocation, false).getChannel();
    trustStoreChannel.write(trustStore);
    trustStoreChannel.close();

    FileUtils.writeStringToFile(passwordFileLocation, password);
}

From source file:com.krawler.portal.tools.FileImpl.java

public void copyFile(File source, File destination, boolean lazy) {
    if (!source.exists()) {
        return;/*  w ww  .  j a  v  a2 s.c  om*/
    }

    if (lazy) {
        String oldContent = null;

        try {
            oldContent = read(source);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
            return;
        }

        String newContent = null;

        try {
            newContent = read(destination);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }

        if ((oldContent == null) || !oldContent.equals(newContent)) {
            copyFile(source, destination, false);
        }
    } else {
        if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) {

            destination.getParentFile().mkdirs();
        }

        try {
            FileChannel srcChannel = new FileInputStream(source).getChannel();
            FileChannel dstChannel = new FileOutputStream(destination).getChannel();

            dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

            srcChannel.close();
            dstChannel.close();
        } catch (IOException ioe) {
            logger.warn(ioe.getMessage(), ioe);
            //            _log.error(ioe.getMessage());
        }
    }
}

From source file:org.multibit.file.FileHandler.java

public static void copyFile(File sourceFile, File destinationFile) throws IOException {
    if (!destinationFile.exists()) {
        destinationFile.createNewFile();
    }/*  w w  w.j a  va 2s .  c o  m*/
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    FileChannel source = null;
    FileChannel destination = null;
    try {
        fileInputStream = new FileInputStream(sourceFile);
        source = fileInputStream.getChannel();
        fileOutputStream = new FileOutputStream(destinationFile);
        destination = fileOutputStream.getChannel();
        long transfered = 0;
        long bytes = source.size();
        while (transfered < bytes) {
            transfered += destination.transferFrom(source, 0, source.size());
            destination.position(transfered);
        }
    } finally {
        if (source != null) {
            source.close();
            source = null;
        } else if (fileInputStream != null) {
            fileInputStream.close();
            fileInputStream = null;
        }
        if (destination != null) {
            destination.close();
            destination = null;
        } else if (fileOutputStream != null) {
            fileOutputStream.flush();
            fileOutputStream.close();
        }
    }
}

From source file:org.cytobank.fcs_files.events.MemoryEvents.java

public MemoryEvents(File doubleFile) throws IOException, MemoryEventsException {
    this.doubleFile = doubleFile;

    numberOfEvents = (int) doubleFile.length() / BYTES_PER_DOUBLE;

    setupMemoryEventsArray(numberOfEvents);

    try {/*from  w w  w  . j a v a 2s . c  om*/
        // Read in the doubles file
        FileInputStream fileInputStream = new FileInputStream(doubleFile);
        FileChannel fileChannel = fileInputStream.getChannel();
        MappedByteBuffer mappedByteBuffer = fileChannel.map(MapMode.READ_ONLY, 0, doubleFile.length());
        DoubleBuffer doubleBuffer = mappedByteBuffer.asDoubleBuffer();

        doubleBuffer.get(events, 0, numberOfEvents);

        fileChannel.close();
        fileInputStream.close();
    } catch (IOException ioe) {
        destroy();
        throw ioe;
    }

    openedAt = System.currentTimeMillis();
}

From source file:it.geosolutions.opensdi2.service.impl.FileUploadServiceImpl.java

/**
 * Create a temporal file with a byte array
 * /* w  w w  .j a v  a2 s . c o m*/
 * @param key of the file
 * @param bytes to write
 * @param i index by the file name
 * @return absolute path to the file
 * @throws IOException
 */
public String createTemporalFile(String key, byte[] bytes, int i) throws IOException {

    String filePath = temporaryFolder + File.separator + key;

    try {

        // write bytes
        File tmpFile = new File(filePath);

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Appending bytes to " + tmpFile.getAbsolutePath());
        }

        // File channel to append bytes
        @SuppressWarnings("resource")
        FileChannel channel = new FileOutputStream(tmpFile, true).getChannel();
        ByteBuffer buf = ByteBuffer.allocateDirect((int) bytes.length);

        // put bytes
        buf.put(bytes);

        // Flips this buffer.  The limit is set to the current position and then
        // the position is set to zero.  If the mark is defined then it is discarded.
        buf.flip();

        // Writes a sequence of bytes to this channel from the given buffer.
        channel.write(buf);

        // close the channel
        channel.close();

    } catch (IOException e) {
        LOGGER.error("Error writing file bytes", e);
    }

    return filePath;
}

From source file:edu.harvard.iq.dvn.ingest.dsb.DSBWrapper.java

public String ingest(StudyFileEditBean file) throws IOException {
    dbgLog.fine("***** DSBWrapper: ingest(): start *****\n");

    String ddi = null;/*www. ja  v a  2  s  .com*/

    BufferedInputStream infile = null;

    // ingest-source file
    File tempFile = new File(file.getTempSystemFileLocation());
    SDIOData sd = null;

    if (file.getControlCardSystemFileLocation() == null) {
        // A "classic", 1 file ingest:        

        String mime_type = file.getStudyFile().getFileType();

        infile = new BufferedInputStream(new FileInputStream(tempFile));

        dbgLog.info("\nfile mimeType=" + mime_type + "\n\n");

        // get available FileReaders for this MIME-type
        Iterator<StatDataFileReader> itr = StatDataIO.getStatDataFileReadersByMIMEType(mime_type);

        if (itr.hasNext()) {
            // use the first Subsettable data reader
            StatDataFileReader sdioReader = itr.next();

            dbgLog.info("reader class name=" + sdioReader.getClass().getName());

            if (mime_type != null) {
                String requestedCharacterEncoding = file.getDataLanguageEncoding();
                if (requestedCharacterEncoding != null) {
                    dbgLog.fine("Will try to process the file assuming that the character strings are "
                            + "encoded in " + requestedCharacterEncoding);
                    sdioReader.setDataLanguageEncoding(requestedCharacterEncoding);
                }
                sd = sdioReader.read(infile, null);
            } else {
                // fail-safe block if mime_type is null
                // check the format type again and then read the file
                dbgLog.info("mime-type was null: use the back-up method");
                sd = StatDataIO.read(infile, null);
            }
        } else {

            throw new IllegalArgumentException(
                    "No FileReader Class found" + " for this mime type=" + mime_type);
        }
    } else {
        // This is a 2-file ingest.
        // As of now, there are 2 supported methods: 
        // 1. CSV raw data file + SPSS control card;
        // 2. TAB raw data file + DDI control card;
        // NOTE, that "POR file with the Extended Labels" is NOT a 2-file.
        // control card-based ingest! Rather, we ingest the file as a regular
        // SPSS/POR dataset, then modify the variable labels in the resulting
        // TabularFile. 

        File rawDataFile = tempFile;

        infile = new BufferedInputStream(new FileInputStream(file.getControlCardSystemFileLocation()));

        String controlCardType = file.getControlCardType();

        if (controlCardType == null || controlCardType.equals("")) {
            dbgLog.info("No Control Card Type supplied.");

            throw new IllegalArgumentException("No Control Card Type supplied.");
        }

        Iterator<StatDataFileReader> itr = StatDataIO.getStatDataFileReadersByFormatName(controlCardType);

        if (!itr.hasNext()) {
            dbgLog.info("No FileReader class found for " + controlCardType + ".");

            throw new IllegalArgumentException("No FileReader Class found for " + controlCardType + ".");
        }

        StatDataFileReader sdioReader = itr.next();

        dbgLog.info("reader class name=" + sdioReader.getClass().getName());

        sd = sdioReader.read(infile, rawDataFile);

    }

    if (sd != null) {
        SDIOMetadata smd = sd.getMetadata();

        // tab-file: source file
        String tabDelimitedDataFileLocation = smd.getFileInformation().get("tabDelimitedDataFileLocation")
                .toString();

        dbgLog.fine("tabDelimitedDataFileLocation=" + tabDelimitedDataFileLocation);

        dbgLog.fine("data file(tempFile): abs path:\n" + file.getTempSystemFileLocation());
        dbgLog.fine("mimeType :\n" + file.getStudyFile().getFileType());

        if (infile != null) {
            infile.close();
        }

        // parse the response
        StudyFile f = file.getStudyFile();

        // first, check dir
        // create a sub-directory "ingested"
        File newDir = new File(tempFile.getParentFile(), "ingested");

        if (!newDir.exists()) {
            newDir.mkdirs();
        }
        dbgLog.fine("newDir: abs path:\n" + newDir.getAbsolutePath());

        // tab-file case: destination
        File newFile = new File(newDir, tempFile.getName());

        // nio-based file-copying idiom
        FileInputStream fis = new FileInputStream(tabDelimitedDataFileLocation);
        FileOutputStream fos = new FileOutputStream(newFile);
        FileChannel fcin = fis.getChannel();
        FileChannel fcout = fos.getChannel();
        fcin.transferTo(0, fcin.size(), fcout);
        fcin.close();
        fcout.close();
        fis.close();
        fos.close();

        dbgLog.fine("newFile: abs path:\n" + newFile.getAbsolutePath());

        // store the tab-file location
        file.setIngestedSystemFileLocation(newFile.getAbsolutePath());

        // finally, if we have an extended variable map, let's replace the 
        // labels that have been found in the data file: 

        if (file.getExtendedVariableLabelMap() != null) {
            for (String varName : file.getExtendedVariableLabelMap().keySet()) {
                if (smd.getVariableLabel().containsKey(varName)) {
                    smd.getVariableLabel().put(varName, file.getExtendedVariableLabelMap().get(varName));
                }
            }
        }

        // return xmlToParse;
        DDIWriter dw = new DDIWriter(smd);
        ddi = dw.generateDDI();

        return ddi;
    }
    return null;
}

From source file:display.containers.FileManager.java

public static boolean copyFile(File from, File to) throws IOException {

    boolean created = to.createNewFile();

    if (created) {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {// w  ww. j a  v  a 2s  . c o  m
            fromChannel = new FileInputStream(from).getChannel();
            toChannel = new FileOutputStream(to).getChannel();

            toChannel.transferFrom(fromChannel, 0, fromChannel.size());

            // set the flags of the to the same as the from
            to.setReadable(from.canRead());
            to.setWritable(from.canWrite());
            to.setExecutable(from.canExecute());
        } finally {
            if (fromChannel != null) {
                fromChannel.close();
            }
            if (toChannel != null) {
                toChannel.close();
            }
            return false;
        }
    }
    return created;
}