Example usage for java.io RandomAccessFile readFully

List of usage examples for java.io RandomAccessFile readFully

Introduction

In this page you can find the example usage for java.io RandomAccessFile readFully.

Prototype

public final void readFully(byte b[]) throws IOException 

Source Link

Document

Reads b.length bytes from this file into the byte array, starting at the current file pointer.

Usage

From source file:be.roots.taconic.pricingguide.util.iTextUtil.java

public static byte[] embedFont(byte[] pdf, String fontFileName, String fontName)
        throws IOException, DocumentException {

    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        // the font file
        RandomAccessFile raf = new RandomAccessFile(fontFileName, "r");
        byte fontfile[] = new byte[(int) raf.length()];
        raf.readFully(fontfile);
        raf.close();/*from  ww  w  .  java2  s  .  co  m*/
        // create a new stream for the font file
        PdfStream stream = new PdfStream(fontfile);
        stream.flateCompress();
        stream.put(PdfName.LENGTH1, new PdfNumber(fontfile.length));
        // create a reader object
        PdfReader reader = new PdfReader(pdf);
        int n = reader.getXrefSize();
        PdfObject object;
        PdfDictionary font;
        PdfStamper stamper = new PdfStamper(reader, baos);
        PdfName fontname = new PdfName(fontName);
        for (int i = 0; i < n; i++) {
            object = reader.getPdfObject(i);
            if (object == null || !object.isDictionary())
                continue;
            font = (PdfDictionary) object;
            if (PdfName.FONTDESCRIPTOR.equals(font.get(PdfName.TYPE1))
                    && fontname.equals(font.get(PdfName.FONTNAME))) {
                PdfIndirectObject objref = stamper.getWriter().addToBody(stream);
                font.put(PdfName.FONTFILE2, objref.getIndirectReference());
            }
        }
        stamper.close();
        reader.close();
        return baos.toByteArray();
    }
}

From source file:org.fusesource.meshkeeper.util.internal.FileSupport.java

static public byte[] read(File file, long pos, int length) throws IOException {
    RandomAccessFile is = new RandomAccessFile(file, "r");
    try {//  w  w  w .  ja  v a2 s .c o  m
        long remaining = is.length() - pos;
        if (remaining < 0) {
            remaining = 0;
        }
        byte rc[] = new byte[(int) Math.min(remaining, length)];
        if (rc.length == 0) {
            return rc;
        }
        is.seek(pos);
        is.readFully(rc);
        return rc;
    } finally {
        is.close();
    }
}

From source file:se.bitcraze.crazyflielib.bootloader.Bootloader.java

public static byte[] readFile(File file) throws IOException {
    byte[] fileData = new byte[(int) file.length()];
    Logger logger = LoggerFactory.getLogger("Bootloader");
    logger.debug("readFile: " + file.getName() + ", size: " + file.length());
    RandomAccessFile raf = null;
    try {/*from   w  w  w.ja va  2 s  .c om*/
        raf = new RandomAccessFile(file.getAbsoluteFile(), "r");
        raf.readFully(fileData);
    } finally {
        if (raf != null) {
            try {
                raf.close();
            } catch (IOException ioe) {
                logger.error(ioe.getMessage());
            }
        }
    }
    return fileData;
}

From source file:org.gcaldaemon.core.sendmail.SendMail.java

private static final String readContent(RandomAccessFile raf) throws Exception {
    String content = null;//from  ww  w  .ja  v a2 s. com
    int len = Math.min((int) raf.length(), 500);
    byte[] bytes = new byte[len];
    raf.seek(0);
    raf.readFully(bytes);
    if (bytes[0] == -17 && bytes[1] == -69 && bytes[2] == -65) {

        // UTF-8 header found
        log.debug("File encoding is 'UTF-8'.");
        bytes = new byte[(int) raf.length() - 3];
        raf.seek(3);
        raf.readFully(bytes);
        content = StringUtils.decodeToString(bytes, StringUtils.UTF_8).trim();
    } else {

        // Autodetect encoding
        String header = StringUtils.decodeToString(bytes, StringUtils.US_ASCII).toUpperCase().replace(':', '=');
        String encoding = null;
        int pos = header.indexOf("ENCODING=");
        if (pos != -1) {
            int end = endOf(header, pos + 10);
            if (end != -1) {
                encoding = header.substring(pos + 9, end);
                encoding = encoding.replace('\'', ' ');
                encoding = encoding.replace('\"', ' ');
                encoding = encoding.trim();
            }
        }

        // Check XML-encoding
        if (encoding == null) {
            pos = header.indexOf("CHARSET=");
            if (pos != -1) {
                int end = endOf(header, pos + 10);
                if (end != -1) {
                    encoding = header.substring(pos + 8, end);
                    encoding = encoding.replace('\'', ' ');
                    encoding = encoding.replace('\"', ' ');
                    encoding = encoding.trim();
                }
            }
        }

        // Convert file encoding to Java encoding
        if (encoding == null) {
            encoding = Charset.defaultCharset().name();
        } else {
            if (encoding.equals("UTF8")) {
                encoding = StringUtils.UTF_8;
            }
        }
        log.debug("File encoding is '" + encoding + "'.");
        bytes = new byte[(int) raf.length()];
        raf.seek(0);
        raf.readFully(bytes);
        content = StringUtils.decodeToString(bytes, encoding).trim();
    }
    return content;
}

From source file:com.sangupta.snowpack.SnowpackRecover.java

/**
 * Try and recover from a chunk./*from www  .  j  a v a  2 s .c o m*/
 * 
 * @param chunkID
 * @param chunkFile
 * @param metadataDB 
 * @return
 * @throws IOException 
 */
private static ChunkInfo recoverChunkInfo(final int chunkID, final File chunkFile,
        SnowpackMetadataDB metadataDB) throws IOException {
    // open the file for reading
    RandomAccessFile raf = new RandomAccessFile(chunkFile, "r");

    // read the length first
    int nameLength, length, terminator, headerLength, numFiles = 0;
    long offset;

    List<FlakeMetadata> metas = new ArrayList<FlakeMetadata>();

    try {
        while (raf.getFilePointer() < raf.length()) {
            offset = raf.getFilePointer();

            nameLength = raf.readInt();
            byte[] name = new byte[nameLength];
            raf.readFully(name);

            length = raf.readInt();
            raf.readLong();
            raf.skipBytes((int) length);

            terminator = raf.readByte();
            if (terminator != 0) {
                System.out.print(" invalid descriptor found...");
                return null;
            }

            headerLength = 4 + name.length + 4 + 8;

            numFiles++;

            metas.add(new FlakeMetadata(new String(name), nameLength, chunkID, offset, headerLength));
        }
    } finally {
        raf.close();
    }

    // all clear for recovery

    // save all metadata in new DB
    for (FlakeMetadata meta : metas) {
        metadataDB.save(meta);
    }

    // return chunk info
    ChunkInfo info = new ChunkInfo();
    info.chunkID = chunkID;
    info.numFiles = numFiles;
    info.writePointer = -1;

    return info;
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * @param file               file do crypt
 * @param encryptionKeyBytes key, either from metadata or {@link EncryptionUtils#generateKey()}
 * @param iv                 initialization vector, either from metadata or {@link EncryptionUtils#randomBytes(int)}
 * @return encryptedFile with encryptedBytes and authenticationTag
 *//*from   ww w . j  a v  a2 s  .c  o  m*/
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static EncryptedFile encryptFile(File file, byte[] encryptionKeyBytes, byte[] iv)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {

    Cipher cipher = Cipher.getInstance(AES_CIPHER);

    Key key = new SecretKeySpec(encryptionKeyBytes, AES);

    GCMParameterSpec spec = new GCMParameterSpec(128, iv);
    cipher.init(Cipher.ENCRYPT_MODE, key, spec);

    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
    byte[] fileBytes = new byte[(int) randomAccessFile.length()];
    randomAccessFile.readFully(fileBytes);

    byte[] cryptedBytes = cipher.doFinal(fileBytes);
    String authenticationTag = encodeBytesToBase64String(
            Arrays.copyOfRange(cryptedBytes, cryptedBytes.length - (128 / 8), cryptedBytes.length));

    return new EncryptedFile(cryptedBytes, authenticationTag);
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * @param file               encrypted file
 * @param encryptionKeyBytes key from metadata
 * @param iv                 initialization vector from metadata
 * @param authenticationTag  authenticationTag from metadata
 * @return decrypted byte[]//  w  w  w.j a  va  2s. com
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static byte[] decryptFile(File file, byte[] encryptionKeyBytes, byte[] iv, byte[] authenticationTag)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchPaddingException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {

    Cipher cipher = Cipher.getInstance(AES_CIPHER);
    Key key = new SecretKeySpec(encryptionKeyBytes, AES);
    GCMParameterSpec spec = new GCMParameterSpec(128, iv);
    cipher.init(Cipher.DECRYPT_MODE, key, spec);

    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
    byte[] fileBytes = new byte[(int) randomAccessFile.length()];
    randomAccessFile.readFully(fileBytes);

    // check authentication tag
    byte[] extractedAuthenticationTag = Arrays.copyOfRange(fileBytes, fileBytes.length - (128 / 8),
            fileBytes.length);

    if (!Arrays.equals(extractedAuthenticationTag, authenticationTag)) {
        throw new SecurityException("Tag not correct");
    }

    return cipher.doFinal(fileBytes);
}

From source file:org.socialnetlib.android.AppdotnetApi.java

private static byte[] readFile(File file) throws IOException {
    // Open file//from   www.ja v a  2  s  .co m
    RandomAccessFile f = new RandomAccessFile(file, "r");

    try {
        // Get and check length
        long longlength = f.length();
        int length = (int) longlength;
        if (length != longlength)
            throw new IOException("File size >= 2 GB");

        // Read file and return data
        byte[] data = new byte[length];
        f.readFully(data);
        return data;
    } finally {
        f.close();
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.file.TarReader.java

/**
 * Scans through the tar file, looking for all segment entries.
 *
 * @throws IOException if the tar file could not be read
 *//*from w  w  w.j a  va  2  s  .  c o  m*/
private static void recoverEntries(File file, RandomAccessFile access, LinkedHashMap<UUID, byte[]> entries)
        throws IOException {
    byte[] header = new byte[BLOCK_SIZE];
    while (access.getFilePointer() + BLOCK_SIZE <= access.length()) {
        // read the tar header block
        access.readFully(header);

        // compute the header checksum
        int sum = 0;
        for (int i = 0; i < BLOCK_SIZE; i++) {
            sum += header[i] & 0xff;
        }

        // identify possible zero block
        if (sum == 0 && access.getFilePointer() + 2 * BLOCK_SIZE == access.length()) {
            return; // found the zero blocks at the end of the file
        }

        // replace the actual stored checksum with spaces for comparison
        for (int i = 148; i < 148 + 8; i++) {
            sum -= header[i] & 0xff;
            sum += ' ';
        }

        byte[] checkbytes = String.format("%06o\0 ", sum).getBytes(UTF_8);
        for (int i = 0; i < checkbytes.length; i++) {
            if (checkbytes[i] != header[148 + i]) {
                log.warn("Invalid entry checksum at offset {} in tar file {}, skipping...",
                        access.getFilePointer() - BLOCK_SIZE, file);
            }
        }

        // The header checksum passes, so read the entry name and size
        ByteBuffer buffer = ByteBuffer.wrap(header);
        String name = readString(buffer, 100);
        buffer.position(124);
        int size = readNumber(buffer, 12);
        if (access.getFilePointer() + size > access.length()) {
            // checksum was correct, so the size field should be accurate
            log.warn("Partial entry {} in tar file {}, ignoring...", name, file);
            return;
        }

        Matcher matcher = NAME_PATTERN.matcher(name);
        if (matcher.matches()) {
            UUID id = UUID.fromString(matcher.group(1));

            String checksum = matcher.group(3);
            if (checksum != null || !entries.containsKey(id)) {
                byte[] data = new byte[size];
                access.readFully(data);

                // skip possible padding to stay at block boundaries
                long position = access.getFilePointer();
                long remainder = position % BLOCK_SIZE;
                if (remainder != 0) {
                    access.seek(position + (BLOCK_SIZE - remainder));
                }

                if (checksum != null) {
                    CRC32 crc = new CRC32();
                    crc.update(data);
                    if (crc.getValue() != Long.parseLong(checksum, 16)) {
                        log.warn("Checksum mismatch in entry {} of tar file {}, skipping...", name, file);
                        continue;
                    }
                }

                entries.put(id, data);
            }
        } else if (!name.equals(file.getName() + ".idx")) {
            log.warn("Unexpected entry {} in tar file {}, skipping...", name, file);
            long position = access.getFilePointer() + size;
            long remainder = position % BLOCK_SIZE;
            if (remainder != 0) {
                position += BLOCK_SIZE - remainder;
            }
            access.seek(position);
        }
    }
}

From source file:net.sf.zekr.common.resource.QuranText.java

/**
 * The private constructor, which loads the whole Quran text from file into memory (<code>quranText</code>
 * )./*w  ww  . ja  v  a  2  s  . c  om*/
 * 
 * @param textType can be either UTHMANI_MODE or SIMPLE_MODE
 * @throws IOException
 */
protected QuranText(int textType) throws IOException {
    mode = textType;
    String qFile = ApplicationPath.SIMPLE_QURAN_TEXT_FILE;
    if (textType == UTHMANI_MODE) {
        qFile = ApplicationPath.UTHMANI_QURAN_TEXT_FILE;
    }

    RandomAccessFile raf = new RandomAccessFile(qFile, "r");
    byte[] buf = new byte[(int) raf.length()];
    raf.readFully(buf);
    rawText = new String(buf, config.getProps().getString("quran.text.encoding"));
    refineRawText();
    raf.close();
}