Example usage for java.nio.channels FileChannel read

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

Introduction

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

Prototype

public final long read(ByteBuffer[] dsts) throws IOException 

Source Link

Document

Reads a sequence of bytes from this channel into the given buffers.

Usage

From source file:RegexProperties.java

public void load(FileInputStream inStream) throws IOException, PatternSyntaxException {
    FileChannel fc = inStream.getChannel();

    ByteBuffer bb = ByteBuffer.allocate((int) fc.size());
    fc.read(bb);
    bb.flip();/*from w w  w  .  j a va2s. c o  m*/
    String fileContent = new String(bb.array());

    Pattern pattern = Pattern.compile("^(.*)$", Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(fileContent);

    while (matcher.find()) {
        String line = matcher.group(1);
        if (line != null && !"".equals(line.trim()) && !line.startsWith("#") && !line.startsWith("!")) {
            String keyValue[] = null;
            if (line.indexOf("=") > 0)
                keyValue = line.split("=", 2);
            else
                keyValue = line.split(":", 2);

            if (keyValue != null) {
                super.put(keyValue[0].trim(), keyValue[1]);
            }
        }
    }
    fc = null;
    bb = null;
}

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

boolean checkFile(File file, String data) {
    FileInputStream fis = null;/*from  ww  w . j ava 2 s  . c  o m*/
    try {
        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: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);
    buffer.rewind();// www . ja va 2 s.c o m
    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);
    buffer.rewind();/*from   w  ww .  jav  a 2 s  . c  o m*/
    decoder.reset();
    String definition = decoder.decode(buffer).toString().trim();
    messageDefinitions.put(pathToMessageName(searchPath, messagePath), definition);
    channel.close();
    inputStream.close();
}

From source file:SelfClassLoader.java

private byte[] loadClassBytes(String className) throws ClassNotFoundException {
    try {/* w w w  . j  a v  a  2s . com*/
        String classFile = getClassFile(className);
        FileInputStream fis = new FileInputStream(classFile);
        FileChannel fileC = fis.getChannel();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        WritableByteChannel outC = Channels.newChannel(baos);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            int i = fileC.read(buffer);
            if (i == 0 || i == -1) {
                break;
            }
            buffer.flip();
            outC.write(buffer);
            buffer.clear();
        }
        fis.close();
        return baos.toByteArray();
    } catch (IOException fnfe) {
        throw new ClassNotFoundException(className);
    }
}

From source file:org.apache.tajo.tuple.offheap.OffHeapRowBlock.java

public boolean copyFromChannel(FileChannel channel, TableStats stats) throws IOException {
    if (channel.position() < channel.size()) {
        clear();/*from  ww  w.j  av a  2 s  .  c  o m*/

        buffer.clear();
        channel.read(buffer);
        memorySize = buffer.position();

        while (position < memorySize) {
            long recordPtr = address + position;

            if (remain() < SizeOf.SIZE_OF_INT) {
                channel.position(channel.position() - remain());
                memorySize = (int) (memorySize - remain());
                return true;
            }

            int recordSize = UNSAFE.getInt(recordPtr);

            if (remain() < recordSize) {
                channel.position(channel.position() - remain());
                memorySize = (int) (memorySize - remain());
                return true;
            }

            position += recordSize;
            rowNum++;
        }

        return true;
    } else {
        return false;
    }
}

From source file:ar.com.init.agros.license.LicenseVerifier.java

private boolean isMasterLicense(String file) throws IOException, FileNotFoundException {
    File licenseFile = new File(file);
    FileChannel fc = (new FileInputStream(licenseFile)).getChannel();
    byte[] bytes = new byte[(int) fc.size()];
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    fc.read(bb);
    String hash = DigestUtils.md5Hex(bytes);
    fc.close();//from   w w w .jav  a  2 s .  c  om
    boolean isMaster = hash.equals(MASTER_LICENSE_HASH);
    return isMaster;
}

From source file:com.twinsoft.convertigo.beans.steps.WriteXMLStep.java

protected void writeFile(String filePath, NodeList nodeList) throws EngineException {
    if (nodeList == null) {
        throw new EngineException("Unable to write to xml file: element is Null");
    }/*from  w  w w  .  j  a  v a  2  s .  c  om*/

    String fullPathName = getAbsoluteFilePath(filePath);
    synchronized (Engine.theApp.filePropertyManager.getMutex(fullPathName)) {
        try {
            String encoding = getEncoding();
            encoding = encoding.length() > 0 && Charset.isSupported(encoding) ? encoding : "UTF-8";
            if (!isReallyAppend(fullPathName)) {
                String tTag = defaultRootTagname.length() > 0 ? StringUtils.normalize(defaultRootTagname)
                        : "document";
                FileUtils.write(new File(fullPathName),
                        "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n<" + tTag + "/>", encoding);
            }

            StringBuffer content = new StringBuffer();

            /* do the content, only append child element */
            for (int i = 0; i < nodeList.getLength(); i++) {
                if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
                    content.append(XMLUtils.prettyPrintElement((Element) nodeList.item(i), true, true));
                }
            }

            /* detect current xml encoding */
            RandomAccessFile randomAccessFile = null;
            try {
                randomAccessFile = new RandomAccessFile(fullPathName, "rw");
                FileChannel fc = randomAccessFile.getChannel();
                ByteBuffer buf = ByteBuffer.allocate(60);
                int nb = fc.read(buf);
                String sbuf = new String(buf.array(), 0, nb, "ASCII");
                String enc = sbuf.replaceFirst("^.*encoding=\"", "").replaceFirst("\"[\\d\\D]*$", "");

                if (!Charset.isSupported(enc)) {
                    enc = encoding;
                }

                buf.clear();

                /* retrieve last header tag*/
                long pos = fc.size() - buf.capacity();
                if (pos < 0) {
                    pos = 0;
                }

                nb = fc.read(buf, pos);

                boolean isUTF8 = Charset.forName(enc) == Charset.forName("UTF-8");

                if (isUTF8) {
                    for (int i = 0; i < buf.capacity(); i++) {
                        sbuf = new String(buf.array(), i, nb - i, enc);
                        if (!sbuf.startsWith("")) {
                            pos += i;
                            break;
                        }
                    }
                } else {
                    sbuf = new String(buf.array(), 0, nb, enc);
                }

                int lastTagIndex = sbuf.lastIndexOf("</");
                if (lastTagIndex == -1) {
                    int iend = sbuf.lastIndexOf("/>");
                    if (iend != -1) {
                        lastTagIndex = sbuf.lastIndexOf("<", iend);
                        String tagname = sbuf.substring(lastTagIndex + 1, iend);
                        content = new StringBuffer(
                                "<" + tagname + ">\n" + content.toString() + "</" + tagname + ">");
                    } else {
                        throw new EngineException("Malformed XML file");
                    }
                } else {
                    content.append(sbuf.substring(lastTagIndex));

                    if (isUTF8) {
                        String before = sbuf.substring(0, lastTagIndex);
                        lastTagIndex = before.getBytes(enc).length;
                    }
                }
                fc.write(ByteBuffer.wrap(content.toString().getBytes(enc)), pos + lastTagIndex);
            } finally {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            }
        } catch (IOException e) {
            throw new EngineException("Unable to write to xml file", e);
        } finally {
            Engine.theApp.filePropertyManager.releaseMutex(fullPathName);
        }
    }
}

From source file:Main.java

public static long findCentralDirStartOffset(final FileChannel fileChannel, final long commentLength)
        throws IOException {
    // End of central directory record (EOCD)
    // Offset    Bytes     Description[23]
    // 0           4       End of central directory signature = 0x06054b50
    // 4           2       Number of this disk
    // 6           2       Disk where central directory starts
    // 8           2       Number of central directory records on this disk
    // 10          2       Total number of central directory records
    // 12          4       Size of central directory (bytes)
    // 16          4       Offset of start of central directory, relative to start of archive
    // 20          2       Comment length (n)
    // 22          n       Comment
    // For a zip with no archive comment, the
    // end-of-central-directory record will be 22 bytes long, so
    // we expect to find the EOCD marker 22 bytes from the end.

    final ByteBuffer zipCentralDirectoryStart = ByteBuffer.allocate(4);
    zipCentralDirectoryStart.order(ByteOrder.LITTLE_ENDIAN);
    fileChannel.position(fileChannel.size() - commentLength - 6); // 6 = 2 (Comment length) + 4 (Offset of start of central directory, relative to start of archive)
    fileChannel.read(zipCentralDirectoryStart);
    final long centralDirStartOffset = zipCentralDirectoryStart.getInt(0);
    return centralDirStartOffset;
}

From source file:tachyon.shell.command.CopyFromLocalCommand.java

private void copyPath(File src, TachyonURI dstPath) throws IOException {
    try {// w w w  . jav a 2  s. c om
        if (!src.isDirectory()) {
            // If the dstPath is a directory, then it should be updated to be the path of the file where
            // src will be copied to
            if (mFileSystem.exists(dstPath) && mFileSystem.getStatus(dstPath).isFolder()) {
                dstPath = dstPath.join(src.getName());
            }

            Closer closer = Closer.create();
            FileOutStream os = null;
            try {
                os = closer.register(mFileSystem.createFile(dstPath));
                FileInputStream in = closer.register(new FileInputStream(src));
                FileChannel channel = closer.register(in.getChannel());
                ByteBuffer buf = ByteBuffer.allocate(8 * Constants.MB);
                while (channel.read(buf) != -1) {
                    buf.flip();
                    os.write(buf.array(), 0, buf.limit());
                }
            } catch (IOException e) {
                // Close the out stream and delete the file, so we don't have an incomplete file lying
                // around
                if (os != null) {
                    os.cancel();
                    if (mFileSystem.exists(dstPath)) {
                        mFileSystem.delete(dstPath);
                    }
                }
                throw e;
            } finally {
                closer.close();
            }
        } else {
            mFileSystem.createDirectory(dstPath);
            List<String> errorMessages = Lists.newArrayList();
            String[] fileList = src.list();
            for (String file : fileList) {
                TachyonURI newPath = new TachyonURI(dstPath, new TachyonURI(file));
                File srcFile = new File(src, file);
                try {
                    copyPath(srcFile, newPath);
                } catch (IOException e) {
                    errorMessages.add(e.getMessage());
                }
            }
            if (errorMessages.size() != 0) {
                if (errorMessages.size() == fileList.length) {
                    // If no files were created, then delete the directory
                    if (mFileSystem.exists(dstPath)) {
                        mFileSystem.delete(dstPath);
                    }
                }
                throw new IOException(Joiner.on('\n').join(errorMessages));
            }
        }
    } catch (TachyonException e) {
        throw new IOException(e.getMessage());
    }
}