Example usage for java.io RandomAccessFile readByte

List of usage examples for java.io RandomAccessFile readByte

Introduction

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

Prototype

public final byte readByte() throws IOException 

Source Link

Document

Reads a signed eight-bit value from this file.

Usage

From source file:com.github.nlloyd.hornofmongo.MongoScope.java

public static Object fuzzFile(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    if (args.length != 2)
        Context.throwAsScriptRuntimeEx(new MongoScriptException("fuzzFile takes 2 arguments"));
    File fileToFuzz;//from   ww  w. ja  va 2s . c om
    try {
        fileToFuzz = resolveFilePath((MongoScope) thisObj, Context.toString(args[0])).getCanonicalFile();
    } catch (IOException e) {
        Context.throwAsScriptRuntimeEx(new MongoScriptException(e));
        return null;
    }
    RandomAccessFile fuzzFile = null;
    try {
        fuzzFile = new RandomAccessFile(fileToFuzz, "rw");
        long fuzzPosition = Double.valueOf(Context.toNumber(args[1])).longValue();
        fuzzFile.seek(fuzzPosition);
        int byteToFuzz = fuzzFile.readByte();
        byteToFuzz = ~byteToFuzz;
        fuzzFile.seek(fuzzPosition);
        fuzzFile.write(byteToFuzz);
        fuzzFile.close();
    } catch (FileNotFoundException e) {
        Context.throwAsScriptRuntimeEx(e);
    } catch (IOException e) {
        Context.throwAsScriptRuntimeEx(e);
    } finally {
        if (fuzzFile != null) {
            try {
                fuzzFile.close();
            } catch (IOException e) {
            }
        }
    }

    return Undefined.instance;
}

From source file:org.slc.sli.sample.transform.CcsCsvReader.java

private String tail(File file) {
    try {/*w  ww .j av  a  2s  .com*/
        RandomAccessFile fileHandler = new RandomAccessFile(file, "r");
        long fileLength = file.length() - 1;
        long filePointer;

        for (filePointer = fileLength; filePointer != -1; filePointer--) {
            fileHandler.seek(filePointer);
            int readByte = fileHandler.readByte();

            if (readByte == 0xA) {
                if (filePointer == fileLength) {
                    continue;
                } else {
                    break;
                }
            } else if (readByte == 0xD) {
                if (filePointer == fileLength - 1) {
                    continue;
                } else {
                    break;
                }
            }

        }

        String lastLine = fileHandler.readLine();
        fileHandler.close();

        return lastLine.substring(1);
    } catch (java.io.FileNotFoundException e) {
        e.printStackTrace();
        return null;
    } catch (java.io.IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:CreateEmployeeFile.java

void read(RandomAccessFile raf) throws IOException {
    char[] temp = new char[15];
    for (int i = 0; i < temp.length; i++)
        temp[i] = raf.readChar();//from  w  w  w  . ja  v  a2s  .  c o  m
    lastName = new String(temp);
    temp = new char[15];
    for (int i = 0; i < temp.length; i++)
        temp[i] = raf.readChar();
    firstName = new String(temp);
    temp = new char[30];
    for (int i = 0; i < temp.length; i++)
        temp[i] = raf.readChar();

    address = new String(temp);
    age = raf.readByte();
    salary = raf.readDouble();
}

From source file:org.patientview.monitoring.ImportMonitor.java

/**
 * Returns the last N lines of a file. Assumes lines are terminated by |n ascii character
 */// w  w  w . j  av a 2 s . c o  m
private static List<String> getLastNLinesOfFile(int numberOfLinesToReturn) {
    List<String> lastNLines = new ArrayList<String>();
    java.io.RandomAccessFile fileHandler = null;

    try {
        File file = getTodaysCountFile();

        fileHandler = new java.io.RandomAccessFile(file, "r");

        long totalNumberOfCharactersInFile = file.length() - 1;

        StringBuilder sb = new StringBuilder();
        int numberOfLinesRead = 0;

        /**
         * loop through characters in file, construct lines out of characters, add lines to a list
         */
        for (long currentCharacter = totalNumberOfCharactersInFile; currentCharacter != -1; currentCharacter--) {
            fileHandler.seek(currentCharacter);

            int readByte = fileHandler.readByte();

            if (readByte == LINE_FEED || readByte == CARRIAGE_RETURN) {
                if (numberOfLinesRead == numberOfLinesToReturn) {
                    break;
                }

                numberOfLinesRead++;

                /**
                 * add line to line list
                 */
                String currentLine = sb.reverse().toString();
                sb = new StringBuilder();

                if (StringUtils.isNotBlank(currentLine)) {
                    lastNLines.add(currentLine);
                } else {
                    LOGGER.error("Read line does not contain any data");
                    continue;
                }
            } else {
                sb.append((char) readByte);
            }
        }

        /**
         * add the last line
         */
        lastNLines.add(sb.reverse().toString());
    } catch (Exception e) {
        LOGGER.error("Can not find today's file", e);
    } finally {
        if (fileHandler != null) {
            try {
                fileHandler.close();
            } catch (IOException e) {
                fileHandler = null;
            }
        }
    }

    return lastNLines;
}

From source file:com.qumasoft.qvcslib.CompareFilesWithApacheDiff.java

private CompareLineInfo[] buildLinesFromFile(File inFile) throws IOException {
    List<CompareLineInfo> lineInfoList = new ArrayList<>();
    RandomAccessFile randomAccessFile = new RandomAccessFile(inFile, "r");
    long fileLength = randomAccessFile.length();
    int startOfLineSeekPosition = 0;
    int currentSeekPosition = 0;
    byte character;
    while (currentSeekPosition < fileLength) {
        character = randomAccessFile.readByte();
        currentSeekPosition = (int) randomAccessFile.getFilePointer();
        if (character == '\n') {
            int endOfLine = (int) randomAccessFile.getFilePointer();
            byte[] buffer = new byte[endOfLine - startOfLineSeekPosition];
            randomAccessFile.seek(startOfLineSeekPosition);
            randomAccessFile.readFully(buffer);
            String line = new String(buffer, UTF8);
            CompareLineInfo lineInfo = new CompareLineInfo(startOfLineSeekPosition, createCompareLine(line));
            lineInfoList.add(lineInfo);/* www  .j av  a2s . c om*/
            startOfLineSeekPosition = endOfLine;
        }
    }
    // Add the final line which can happen if it doesn't end in a newline.
    if ((fileLength - startOfLineSeekPosition) > 0L) {
        byte[] buffer = new byte[(int) fileLength - startOfLineSeekPosition];
        randomAccessFile.seek(startOfLineSeekPosition);
        randomAccessFile.readFully(buffer);
        String line = new String(buffer, UTF8);
        CompareLineInfo lineInfo = new CompareLineInfo(startOfLineSeekPosition, createCompareLine(line));
        lineInfoList.add(lineInfo);
    }
    CompareLineInfo[] lineInfoArray = new CompareLineInfo[lineInfoList.size()];
    int i = 0;
    for (CompareLineInfo lineInfo : lineInfoList) {
        lineInfoArray[i++] = lineInfo;
    }
    return lineInfoArray;
}

From source file:raptor.service.DictionaryService.java

public String[] getWordsThatStartWith(String string) {
    List<String> result = new ArrayList<String>(10);

    string = string.toLowerCase();//from w  w w  . ja va  2 s  .co m
    long startTime = System.currentTimeMillis();
    RandomAccessFile raf = null;
    try {
        File file = new File(DICTIONARY_PATH);
        raf = new RandomAccessFile(file, "r");

        long low = 0;
        long high = file.length();

        long p = -1;
        while (low < high) {
            long mid = (low + high) / 2;
            p = mid;
            while (p >= 0) {
                raf.seek(p);

                char c = (char) raf.readByte();
                if (c == '\n')
                    break;
                p--;
            }
            if (p < 0)
                raf.seek(0);
            String line = raf.readLine();
            // Useful for debugging
            // System.out.println("-- " + mid + " " + line);
            if (line == null) {
                low = high;
            } else {
                int compare = line.compareTo(string);
                if (compare < 0) {
                    low = mid + 1;
                } else if (compare == 0) {
                    low = p;
                    break;
                } else {
                    high = mid;
                }
            }
        }

        p = low;
        while (p >= 0 && p < high) {
            raf.seek(p);
            if (((char) raf.readByte()) == '\n')
                break;
            p--;
        }

        if (p < 0)
            raf.seek(0);

        String line = raf.readLine();
        while (line != null && line.startsWith(string)) {
            result.add(line);
            line = raf.readLine();
        }
    } catch (Throwable t) {
        Raptor.getInstance().onError("Error reading dictionary file: " + DICTIONARY_PATH, t);
    } finally {
        try {
            raf.close();
        } catch (Throwable t) {
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Searched " + string + " (" + (System.currentTimeMillis() - startTime) + ") " + result);
        }

    }
    return result.toArray(new String[0]);
}

From source file:raptor.service.DictionaryService.java

/**
 * This method started out as code from//from  www  . j  av a 2  s.  c o  m
 * http://stackoverflow.com/questions/736556/binary
 * -search-in-a-sorted-memory-mapped-file-in-java
 * 
 * It has been altered to fix some bugs.
 */
protected boolean binarySearch(String filename, String string) {
    string = string.toLowerCase();
    long startTime = System.currentTimeMillis();
    RandomAccessFile raf = null;
    boolean result = false;
    try {
        File file = new File(filename);
        raf = new RandomAccessFile(file, "r");

        long low = 0;
        long high = file.length();

        long p = -1;
        while (low < high) {
            long mid = (low + high) / 2;
            p = mid;
            while (p >= 0) {
                raf.seek(p);

                char c = (char) raf.readByte();
                if (c == '\n')
                    break;
                p--;
            }
            if (p < 0)
                raf.seek(0);
            String line = raf.readLine();
            // Useful for debugging
            // System.out.println("-- " + mid + " " + line);
            if (line == null) {
                low = high;
            } else {
                int compare = line.compareTo(string);
                if (compare < 0) {
                    low = mid + 1;
                } else if (compare == 0) {
                    return true;
                } else {
                    high = mid;
                }
            }
        }

        p = low;
        while (p >= 0 && p < high) {
            raf.seek(p);
            if (((char) raf.readByte()) == '\n')
                break;
            p--;
        }

        if (p < 0)
            raf.seek(0);

        while (true) {
            String line = raf.readLine();
            // Useful for debugging.
            // System.out.println("searching forwards " + line);
            if (line == null) {
                result = false;
                break;
            } else if (line.equals(string)) {
                result = true;
                break;
            } else if (!line.startsWith(string)) {
                result = false;
                break;
            }
        }
    } catch (Throwable t) {
        Raptor.getInstance().onError("Error reading dictionary file: " + DICTIONARY_PATH, t);
    } finally {
        try {
            raf.close();
        } catch (Throwable t) {
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Searched " + string + " (" + (System.currentTimeMillis() - startTime) + ") " + result);
        }

    }
    return result;
}

From source file:com.alu.e3.logger.LogCollector.java

private static String getTailOfFile(File file, int numLines) throws FileNotFoundException, IOException {
    if (numLines < 0) {
        return null;
    } else if (numLines == 0) {
        return "";
    }/*from  w w  w  .  j  a  v a  2s  .  c  o  m*/
    java.io.RandomAccessFile raFile = new java.io.RandomAccessFile(file, "r");
    long fileLength = file.length() - 1;
    StringBuilder sb = new StringBuilder();
    int line = 0;

    for (long filePointer = fileLength; filePointer >= 0; filePointer--) {
        raFile.seek(filePointer);
        int readByte = raFile.readByte();

        if (readByte == 0xA) {
            if (filePointer < fileLength) {
                line = line + 1;
                if (line >= numLines) {
                    break;
                }
            }
        }
        sb.append((char) readByte);
    }

    String lastLines = sb.reverse().toString();
    return lastLines;
}

From source file:TarList.java

public TarEntry(RandomAccessFile is) throws IOException, TarException {

    fileOffset = is.getFilePointer();/*from  w  w w.  ja  v  a 2  s . com*/

    // read() returns -1 at EOF
    if (is.read(name) < 0)
        throw new EOFException();
    // Tar pads to block boundary with nulls.
    if (name[0] == '\0')
        throw new EOFException();
    // OK, read remaining fields.
    is.read(mode);
    is.read(uid);
    is.read(gid);
    is.read(size);
    is.read(mtime);
    is.read(chksum);
    type = is.readByte();
    is.read(linkName);
    is.read(magic);
    is.read(uname);
    is.read(gname);
    is.read(devmajor);
    is.read(devminor);

    // Since the tar header is < 512, we need to skip it.
    is.skipBytes((int) (TarFile.RECORDSIZE - (is.getFilePointer() % TarFile.RECORDSIZE)));

    // TODO if checksum() fails,
    //   throw new TarException("Failed to find next header");

}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
 * We have the password from initializing the class. pass the iv and salt here which is
 * obtained when encrypting the file initially.
 *
 * @param inFile - The Encrypted File containing encrypted data , salt and InitVec
 * @throws NoSuchAlgorithmException/*from   w  w w . ja  v  a2  s.co m*/
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 * @throws IOException
 */
public void setupDecrypt(File inFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, DecoderException, IOException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    byte[] vSalt = new byte[8];
    byte[] vInitVec = new byte[16];

    RandomAccessFile vFile = new RandomAccessFile(inFile, "rw");

    //The last 8 bits are salt so seek to length of file minus 9 bits
    vFile.seek(vFile.length() - 8);
    vFile.readFully(vSalt);

    //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24
    //Thus to seek to length of file minus 24 bits
    vFile.seek(vFile.length() - 24);
    vFile.readFully(vInitVec);
    vFile.seek(0);

    File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file");

    RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw");

    for (int i = 0; i < (vFile.length() - 24); ++i) {
        vTmpFile.write(vFile.readByte());
    }
    vFile.close();
    vTmpFile.close();

    inFile.delete();
    tmpFile.renameTo(inFile);

    Db("got salt " + Hex.encodeHexString(vSalt));

    Db("got initvector :" + Hex.encodeHexString(vInitVec));

    /* Derive the key, given password and salt. */
    // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
    // The end user must also install them (not compiled in) so beware.
    // see here:
    // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
    // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function
    //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard)

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);

    tmp = factory.generateSecret(spec);
    secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    // Decrypt the message, given derived key and initialization vector.
    vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec));
}