Example usage for java.nio.channels FileChannel map

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

Introduction

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

Prototype

public abstract MappedByteBuffer map(MapMode mode, long position, long size) throws IOException;

Source Link

Document

Maps a region of this channel's file directly into memory.

Usage

From source file:configuration.Util.java

/** Fast & simple file copy. */
public static void copy(File source, File dest) throws IOException {
    FileChannel in = null, out = null;
    try {/*from  ww  w  . ja  va2  s .c  o  m*/
        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);

    } catch (Exception e) {
        System.out.println("Copy File Directory Failed!");
        System.out.println(e);
    }
    if (in != null)
        in.close();
    if (out != null)
        out.close();
}

From source file:com.rapidminer.tools.Tools.java

public static void copy(File srcPath, File dstPath) throws IOException {
    if (srcPath.isDirectory()) {
        if (!dstPath.exists()) {
            boolean result = dstPath.mkdir();
            if (!result) {
                throw new IOException("Unable to create directoy: " + dstPath);
            }/*ww  w . j  av a 2 s  . co m*/
        }

        String[] files = srcPath.list();
        for (String file : files) {
            copy(new File(srcPath, file), new File(dstPath, file));
        }
    } else {
        if (srcPath.exists()) {
            FileChannel in = null;
            FileChannel out = null;
            try (FileInputStream fis = new FileInputStream(srcPath);
                    FileOutputStream fos = new FileOutputStream(dstPath)) {
                in = fis.getChannel();
                out = fos.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:org.wandora.application.gui.topicpanels.ProcessingTopicPanel.java

private String buildSource(String sketch) {
    boolean useTemplate = false; // maybe make this an option in the future

    try {/*from   w  ww  .j  ava 2 s .  co m*/
        //            classIdentifier = System.currentTimeMillis();
        if (useTemplate) {
            //                processingClassName="SketchTemplate";

            String sketchTemplate = "";
            FileInputStream stream = new FileInputStream(new File(sketchPath + "SketchTemplate.java"));

            try {
                FileChannel fc = stream.getChannel();
                MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
                /* Instead of using default, pass in a decoder. */
                sketchTemplate = Charset.defaultCharset().decode(bb).toString();
            } finally {
                stream.close();
            }
            String upperPart = sketchTemplate.substring(0, sketchTemplate.indexOf(tempReplaceStart) + 1);
            linesBeforeCode = upperPart.split(System.getProperty("line.separator")).length - 1;
            //System.out.println("Lines before code "+linesBeforeCode);

            charactersBefore = sketchTemplate.indexOf(tempReplaceStart);
            //temp = temp.substring(temp.indexOf("\n"));

            String fullSource = sketchTemplate.substring(0, sketchTemplate.indexOf(tempReplaceStart)) + sketch
                    + sketchTemplate.substring(sketchTemplate.indexOf(tempReplaceEnd) + tempReplaceEnd.length(),
                            sketchTemplate.length());

            //                fullSource = fullSource.replaceAll("(?:SketchTemplate)", processingClassName+classIdentifier);
            //                fullSource = fullSource.replaceFirst("(?:PApplet)", "SketchTemplate");
            return fullSource;
        } else {
            // (?m) turns on multi-line mode so ^ and $ match line start and end
            Pattern p = Pattern.compile("(?m)^\\s*package\\s+processing\\s*;\\s*$");
            if (!p.matcher(sketch).find()) {
                throw new Exception(
                        "The sketch file must be defined to be in the \"processing\" package. Add \"package processing;\" at the start of the sketch or modify the existing package declaration.");
            }

            return sketch;
        }
    } catch (Exception ex) {
        Logger.getLogger(ProcessingTopicPanel.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }
    return null;
}

From source file:jackpal.androidterm.Term.java

private void copyFileToClipboard(String filename) {
    if (filename == null)
        return;// w w w  .  ja v  a2 s  .  c  om
    FileInputStream fis;
    try {
        fis = new FileInputStream(filename);
        FileChannel fc = fis.getChannel();
        try {
            ByteBuffer bbuf;
            bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0, (int) fc.size());
            // Create a read-only CharBuffer on the file
            CharBuffer cbuf = Charset.forName("UTF-8").newDecoder().decode(bbuf);
            String str = cbuf.toString();
            ClipboardManagerCompat clip = ClipboardManagerCompatFactory.getManager(getApplicationContext());
            clip.setText(str);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:gephi.spade.panel.fcsFile.java

/**
 * extractEvents ---/*from  w ww. java  2  s.com*/
 * <p>
 * Extracts the events from the FCS file using NIO.
 * </p>
 *
 * @throws <code>java.io.FileNotFoundException</code> if the file is not
 *         found.
 * @throws <code>java.io.IOException</code> if an IO exception occurred.
 */
private void extractEvents() throws FileNotFoundException, IOException {
    if ((dataStart >= dataEnd) || (totalEvents <= 0)) {
        // If the byte offset of the start of the DATA segment is greater
        // than or equal to the end of the DATA segment or the number of
        // events is equal to 0, then create an empty array of events.
        eventList = new double[0][parameters];

        return;
    }

    // Open a file input stream to the file
    FileInputStream fis = new FileInputStream(file);

    // Get the channel for the file
    FileChannel fc = fis.getChannel();

    // Map the DATA segment to memory
    MappedByteBuffer data;

    try {
        data = fc.map(FileChannel.MapMode.READ_ONLY, dataStart, dataEnd - dataStart + 1);
    } catch (Throwable t) {
        // Try again with a workaround to see if we can compensate for off-by-one errors that
        // some FCS files have been known to incorporate in the ENDDATA property.
        data = fc.map(FileChannel.MapMode.READ_ONLY, dataStart, dataEnd - dataStart);
    }

    /**
     * We don't need to worry about endian-ness here since ASCII is one
     * byte, and float and double are IEEE standards.
     */
    if (dataType != null) {
        if (dataType.equalsIgnoreCase("I")) {
            // If the data type is "I", then it is binary integer.
            readBinIntData(data);
        } else if (dataType.equalsIgnoreCase("F")) {
            // If the data type is "F", then it is floating point.
            readFloatData(data);
        } else if (dataType.equalsIgnoreCase("D")) {
            // If the data type is "D", then it is double precision floating
            // point
            readDoubleData(data);
        } else if (dataType.equalsIgnoreCase("A")) {
            // If the data type is "A", then it is ASCII.
            readASCIIData(data);
        }
    }

    // Close the file channel
    fc.close();

    // Close the file input stream
    fis.close();
}

From source file:gephi.spade.panel.fcsFile.java

/**
 * readFile ---//from  ww w  .j  a va 2 s  .  c  o  m
 * <p>
 * A helper function to read all the fields in the TEXT segment of the FCS
 * file.
 * </p>
 *
 * <p>
 * This helper function should only be called once by the constructor as it
 * is quite expensive.
 * </p>
 *
 * @param extractEventsP
 *            boolean flag indicating whether to extract events in the
 *            underlying file.
 * @throws <code>java.io.FileNotFoundException</code> if the file is not
 *         found.
 * @throws <code>java.io.IOException</code> if an IO exception occurred.
 */
private void readFile(boolean extractEventsP) throws FileNotFoundException, IOException {
    // Open a file input stream to the file
    FileInputStream fis = new FileInputStream(file);

    // Create a byte array to hold the version
    byte[] versionArray = new byte[VERSION_SIZE];

    // Read the version into the byte array
    int numRead = fis.read(versionArray);

    if (numRead < VERSION_SIZE) {
        // If the number of bytes read is less than the number of bytes in
        // the version string, then the file is too small to be an FCS file.
        isFCSP = false;

        // Close the file input stream
        fis.close();

        // Quit
        return;
    }

    // Decode the version using the default encoding
    version = new String(versionArray);

    // Determine whether the file is an FCS file by whether the version
    // string starts with the FCS_PREFIX
    isFCSP = version.startsWith(FCS_PREFIX);

    if (!isFCSP) {
        // If the file is not an FCS file, then close the file and quit.
        // Close the file input stream
        fis.close();

        // Quit
        return;
    }

    /**
     * At this point, we are pretty sure that the file is an FCS file. So,
     * we parse it.
     */
    /**
     * Get the standard HEADER stuff
     */
    // Skip 4 bytes to get to byte 10
    fis.skip(4);

    // Create a byte array to hold the HEADER
    byte[] headerArray = new byte[48];

    // Read the header into the byte array
    numRead = fis.read(headerArray);

    if (numRead < 48) {
        // If the number of bytes read is less than 48, then the file is too
        // small to be an FCS file.
        isFCSP = false;

        // Close the file input stream
        fis.close();

        // Quit
        return;
    }

    try {
        // Try to parse the TEXT segment start and end and DATA segment
        // start and end
        textStart = Integer.parseInt((new String(headerArray, 0, 8)).trim());
        textEnd = Integer.parseInt((new String(headerArray, 8, 8)).trim());
        dataStart = Integer.parseInt((new String(headerArray, 16, 8)).trim());
        dataEnd = Integer.parseInt((new String(headerArray, 24, 8)).trim());
    } catch (NumberFormatException nfe) {
        // If a NumberFormatException occured, then quit because there's
        // nothing we can do without the TEXT or DATA segment.
        // Close the file input stream
        fis.close();

        return;
    }

    /**
     * Get the ANALYSIS segment limits
     */
    try {
        // Try to parse the analysisStart and analysisEnd
        analysisStart = Integer.parseInt((new String(headerArray, 32, 8)).trim());
        analysisEnd = Integer.parseInt((new String(headerArray, 40, 8)).trim());
    } catch (NumberFormatException nfe) {
        // If a NumberFormatException occured, then set the ANALYSIS start
        // and end to 0 since this segment is optional.
        analysisStart = 0;
        analysisEnd = 0;
    }

    /**
     * Use NIO to read the OTHER and TEXT segments
     */
    // Get the channel for the input file
    FileChannel fc = fis.getChannel();

    // Move the channel's position back to 0
    fc.position(0);

    // Map the TEXT segment to memory
    MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, textEnd + 1);

    /**
     * Create the character decoder for parsing characters
     */
    decoder = charset.newDecoder();

    /**
     * Get the OTHER segment
     */
    mbb.limit(textStart);
    mbb.position(58);
    CharBuffer other = decoder.decode(mbb.slice());

    /**
     * Get the TEXT segment
     */
    mbb.limit(textEnd + 1);
    mbb.position(textStart);
    text = decoder.decode(mbb.slice()).toString();

    /**
     * Close the file since we have the string version of the TEXT segment
     */
    // Close the file channel
    fc.close();

    // Close the file input stream
    fis.close();

    /**
     * Decode the TEXT segment
     */
    // The first character of the primary TEXT segment contains the
    // delimiter character
    delimiter = text.charAt(0);

    /**
     * Key/Value Pairs
     */
    // Generate all the pairs
    String[] pairs;

    if (delimiter == '\\') {
        // If the delimiter character is a backslash, then we have to escape
        // it in the regular expression.
        pairs = text.split("[\\\\]");
    } else {
        // Otherwise, we can just split it normally by using the character
        // in the regular expression.
        pairs = text.split("[" + Character.toString(delimiter) + "]");
    }

    /**
     * Calculate the number of pairs --- The number of pairs is the length
     * of the pairs array minus 1 divided by 2. The one is due to the empty
     * first element from the Java split above.
     */
    int numPairs = (pairs.length - 1) / 2;

    // Create a mapping for each key and its value
    settings = new Properties();

    // Loop through the TEXT segment we just split to get the keys and
    // values
    // The key is in (i * 2) + 1 to account for the empty first element.
    // The value is in (i * 2) + 2 to account for the empty first element.
    for (int i = 0; i < numPairs; i++) {
        settings.setProperty(pairs[(i * 2) + 1].trim(), pairs[(i * 2) + 2].trim());
    }

    // Go through all the key/value pairs and parse them
    parseSettings();

    /**
     * Extract Events
     */
    if (extractEventsP) {
        // If we are extracting data, then do so.
        extractEvents();
    }
}

From source file:org.alfresco.repo.search.impl.lucene.index.IndexInfo.java

private void writeStatusToFile(FileChannel channel) throws IOException {
    long size = getBufferSize();

    ByteBuffer buffer;// ww w.  j a va  2 s  . c  om
    if (useNIOMemoryMapping) {
        MappedByteBuffer mbb = channel.map(MapMode.READ_WRITE, 0, size);
        mbb.load();
        buffer = mbb;
    } else {
        channel.truncate(size);
        buffer = ByteBuffer.wrap(new byte[(int) size]);
    }

    buffer.position(0);

    buffer.putLong(version);
    CRC32 crc32 = new CRC32();
    crc32.update((int) (version >>> 32) & 0xFFFFFFFF);
    crc32.update((int) (version >>> 0) & 0xFFFFFFFF);

    buffer.putInt(indexEntries.size());
    crc32.update(indexEntries.size());

    for (IndexEntry entry : indexEntries.values()) {
        String entryType = entry.getType().toString();
        writeString(buffer, crc32, entryType);

        writeString(buffer, crc32, entry.getName());

        writeString(buffer, crc32, entry.getParentName());

        String entryStatus = entry.getStatus().toString();
        writeString(buffer, crc32, entryStatus);

        writeString(buffer, crc32, entry.getMergeId());

        buffer.putLong(entry.getDocumentCount());
        crc32.update((int) (entry.getDocumentCount() >>> 32) & 0xFFFFFFFF);
        crc32.update((int) (entry.getDocumentCount() >>> 0) & 0xFFFFFFFF);

        buffer.putLong(entry.getDeletions());
        crc32.update((int) (entry.getDeletions() >>> 32) & 0xFFFFFFFF);
        crc32.update((int) (entry.getDeletions() >>> 0) & 0xFFFFFFFF);

        buffer.put(entry.isDeletOnlyNodes() ? (byte) 1 : (byte) 0);
        crc32.update(entry.isDeletOnlyNodes() ? new byte[] { (byte) 1 } : new byte[] { (byte) 0 });
    }
    buffer.putLong(crc32.getValue());

    if (useNIOMemoryMapping) {
        ((MappedByteBuffer) buffer).force();
    } else {
        buffer.rewind();
        channel.position(0);
        channel.write(buffer);
    }
}

From source file:org.alfresco.repo.search.impl.lucene.index.IndexInfo.java

private boolean checkVersion(FileChannel channel) throws IOException {
    if (channel.size() > 0) {
        channel.position(0);//from w w w .ja va2s.co m
        ByteBuffer buffer;

        if (useNIOMemoryMapping) {
            MappedByteBuffer mbb = channel.map(MapMode.READ_ONLY, 0, 8);
            mbb.load();
            buffer = mbb;
        } else {
            buffer = ByteBuffer.wrap(new byte[8]);
            channel.read(buffer);
            buffer.position(0);
        }

        buffer.position(0);
        long onDiskVersion = buffer.getLong();
        return (version == onDiskVersion);
    }
    return (version == 0);
}

From source file:org.alfresco.repo.search.impl.lucene.index.IndexInfo.java

private void setStatusFromFile(FileChannel channel) throws IOException {
    if (channel.size() > 0) {
        channel.position(0);//from w w w .  j  a  v  a  2 s  .  c  o m
        ByteBuffer buffer;

        if (useNIOMemoryMapping) {
            MappedByteBuffer mbb = channel.map(MapMode.READ_ONLY, 0, channel.size());
            mbb.load();
            buffer = mbb;
        } else {
            buffer = ByteBuffer.wrap(new byte[(int) channel.size()]);
            channel.read(buffer);
            buffer.position(0);
        }

        buffer.position(0);
        long onDiskVersion = buffer.getLong();
        if (version != onDiskVersion) {
            CRC32 crc32 = new CRC32();
            crc32.update((int) (onDiskVersion >>> 32) & 0xFFFFFFFF);
            crc32.update((int) (onDiskVersion >>> 0) & 0xFFFFFFFF);
            int size = buffer.getInt();
            crc32.update(size);
            LinkedHashMap<String, IndexEntry> newIndexEntries = new LinkedHashMap<String, IndexEntry>();
            // Not all state is saved some is specific to this index so we
            // need to add the transient stuff.
            // Until things are committed they are not shared unless it is
            // prepared
            for (int i = 0; i < size; i++) {
                String indexTypeString = readString(buffer, crc32);
                IndexType indexType;
                try {
                    indexType = IndexType.valueOf(indexTypeString);
                } catch (IllegalArgumentException e) {
                    throw new IOException("Invalid type " + indexTypeString);
                }

                String name = readString(buffer, crc32);

                String parentName = readString(buffer, crc32);

                String txStatus = readString(buffer, crc32);
                TransactionStatus status;
                try {
                    status = TransactionStatus.valueOf(txStatus);
                } catch (IllegalArgumentException e) {
                    throw new IOException("Invalid status " + txStatus);
                }

                String mergeId = readString(buffer, crc32);

                long documentCount = buffer.getLong();
                crc32.update((int) (documentCount >>> 32) & 0xFFFFFFFF);
                crc32.update((int) (documentCount >>> 0) & 0xFFFFFFFF);

                long deletions = buffer.getLong();
                crc32.update((int) (deletions >>> 32) & 0xFFFFFFFF);
                crc32.update((int) (deletions >>> 0) & 0xFFFFFFFF);

                byte deleteOnlyNodesFlag = buffer.get();
                crc32.update(deleteOnlyNodesFlag);
                boolean isDeletOnlyNodes = deleteOnlyNodesFlag == 1;

                if (!status.isTransient()) {
                    newIndexEntries.put(name, new IndexEntry(indexType, name, parentName, status, mergeId,
                            documentCount, deletions, isDeletOnlyNodes));
                }
            }
            long onDiskCRC32 = buffer.getLong();
            if (crc32.getValue() == onDiskCRC32) {
                for (IndexEntry entry : indexEntries.values()) {
                    if (entry.getStatus().isTransient()) {
                        newIndexEntries.put(entry.getName(), entry);
                    }
                }
                version = onDiskVersion;
                indexEntries = newIndexEntries;
            } else {
                throw new IOException("Invalid file check sum");
            }
        }
    }

}

From source file:com.linkedin.databus.core.DbusEventBuffer.java

public static ByteBuffer allocateByteBuffer(int size, ByteOrder byteOrder, AllocationPolicy allocationPolicy,
        boolean restoreBuffers, File mmapSessionDir, File mmapFile) {
    ByteBuffer buffer = null;// ww w .  java 2 s.  c  o  m

    switch (allocationPolicy) {
    case HEAP_MEMORY:
        buffer = ByteBuffer.allocate(size).order(byteOrder);
        break;
    case DIRECT_MEMORY:
        buffer = ByteBuffer.allocateDirect(size).order(byteOrder);
        break;
    case MMAPPED_MEMORY:
    default:
        // expect that dirs are already created and initialized
        if (!mmapSessionDir.exists()) {
            throw new RuntimeException(mmapSessionDir.getAbsolutePath() + " doesn't exist");
        }

        if (restoreBuffers) {
            if (!mmapFile.exists()) {
                LOG.warn("restoreBuffers is true, but file " + mmapFile + " doesn't exist");
            } else {
                LOG.info("restoring buffer from " + mmapFile);
            }
        } else {
            if (mmapFile.exists()) {
                // this path should never happen (only if the generated session ID accidentally matches a previous one)
                LOG.info("restoreBuffers is false; deleting existing mmap file " + mmapFile);
                if (!mmapFile.delete()) {
                    throw new RuntimeException("deletion of file failed: " + mmapFile.getAbsolutePath());
                }
            }
            LOG.info("restoreBuffers is false => will delete new mmap file " + mmapFile + " on exit");
            mmapFile.deleteOnExit(); // in case we don't need files later.
        }

        try {
            FileChannel rwChannel = new RandomAccessFile(mmapFile, "rw").getChannel();
            buffer = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, size).order(byteOrder);
            rwChannel.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(
                    "[should never happen!] can't find mmap file/dir " + mmapFile.getAbsolutePath(), e);
        } catch (IOException e) {
            throw new RuntimeException("unable to initialize mmap file " + mmapFile, e);
        }
    }
    return buffer;
}