List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
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// w w w . j a va 2 s .c om * @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)); }
From source file:com.aliyun.odps.volume.VolumeFSInputStream.java
private synchronized InputStream getLocalInputStream(long index) throws FileNotFoundException, IOException { if (!seekOptimization) { return null; }//from ww w. j ava 2 s . c o m isCache = true; File blockFile = new File(buffer_block_dir, getBlockFileName(index)); raf = new RandomAccessFile(blockFile, "r"); return Channels.newInputStream(raf.getChannel().position(pos - curIndex * blockSize)); }
From source file:de.cosmocode.palava.store.FileSystemStore.java
@Override public ByteBuffer view(String identifier) throws IOException { Preconditions.checkNotNull(identifier, "Identifier"); final File file = getFile(identifier); Preconditions.checkState(file.exists(), "%s does not exist", file); LOG.trace("Reading file from {}", file); final FileChannel channel = new RandomAccessFile(file, "r").getChannel(); return channel.map(MapMode.READ_ONLY, 0, channel.size()); }
From source file:com.geekandroid.sdk.pay.utils.Util.java
public static byte[] readFromFile(String fileName, int offset, int len) { if (fileName == null) { return null; }/* www .j av a2s . c o m*/ File file = new File(fileName); if (!file.exists()) { Log.i(TAG, "readFromFile: file not found"); return null; } if (len == -1) { len = (int) file.length(); } Log.d(TAG, "readFromFile : offset = " + offset + " len = " + len + " offset + len = " + (offset + len)); if (offset < 0) { Log.e(TAG, "readFromFile invalid offset:" + offset); return null; } if (len <= 0) { Log.e(TAG, "readFromFile invalid len:" + len); return null; } if (offset + len > (int) file.length()) { Log.e(TAG, "readFromFile invalid file len:" + file.length()); return null; } byte[] b = null; try { RandomAccessFile in = new RandomAccessFile(fileName, "r"); b = new byte[len]; // ?? in.seek(offset); in.readFully(b); in.close(); } catch (Exception e) { Log.e(TAG, "readFromFile : errMsg = " + e.getMessage()); e.printStackTrace(); } return b; }
From source file:com.sun.faban.harness.webclient.ResultAction.java
private String editResultInfo(String runID) throws FileNotFoundException, IOException { RunId runId = new RunId(runID); String ts = null;// ww w . j a va2 s . c om String[] status = new String[2]; File file = new File(Config.OUT_DIR + runID + '/' + Config.RESULT_INFO); RandomAccessFile rf = new RandomAccessFile(file, "rwd"); long size = rf.length(); byte[] buffer = new byte[(int) size]; rf.readFully(buffer); String content = new String(buffer, 0, (int) size); int idx = content.indexOf('\t'); if (idx != -1) { status[0] = content.substring(0, idx).trim(); status[1] = content.substring(++idx).trim(); } else { status[0] = content.trim(); int lastIdxln = status[0].lastIndexOf("\n"); if (lastIdxln != -1) status[0] = status[0].substring(0, lastIdxln - 1); } if (status[1] != null) { ts = status[1]; } else { String paramFileName = runId.getResultDir().getAbsolutePath() + File.separator + "run.xml"; File paramFile = new File(paramFileName); long dt = paramFile.lastModified(); ts = dateFormat.format(new Date(dt)); rf.seek(rf.length()); rf.writeBytes('\t' + ts.trim()); } rf.close(); return ts; }
From source file:dk.statsbiblioteket.util.LineReaderTest.java
public void testVsRandomAccess() throws Exception { RandomAccessFile ra = new RandomAccessFile(logfile, "r"); LineReader lr = new LineReader(logfile, "r"); int count = 0; while (count++ < LINES) { assertEquals("The lr line should match ra line", ++count + "'" + fixISO(ra.readLine()) + "'", count + "'" + lr.readLine() + "'"); }//w ww . ja v a 2s . c o m }
From source file:com.sangupta.snowpack.SnowpackRecover.java
/** * Try and recover from a chunk./*from w w w . j a va 2 s .co 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.slytechs.capture.StreamFactory.java
public InputCapture<? extends CapturePacket> newInput(final File file, final Filter<ProtocolFilterTarget> filter) throws IOException { final BufferedInputStream b = new BufferedInputStream(new FileInputStream(file)); b.mark(1024); // Buffer first 1K of stream so we can rewind /*/*ww w. j av a2s. c o m*/ * Check the stream, without decompression first */ if (formatType(Channels.newChannel(b)) != null) { b.close(); /* * This is a plain uncompressed file, open up a FileChannel. It will be * much faster */ return newInput(new RandomAccessFile(file, "rw").getChannel(), filter); } /* * Try with gunziped stream, second */ b.reset(); // Rewind if (formatType(Channels.newChannel(new GZIPInputStream(b))) != null) { b.close(); /* * Now reopen the same file, but this time without the buffered * inputstream in the middle. Try to make things as efficient as possible. * TODO: implement much faster channel based GZIP decompression algorithm */ return newInput(Channels.newChannel(new GZIPInputStream(new FileInputStream(file))), filter); } b.close(); return factoryForOther.getFactory().newInput(new RandomAccessFile(file, "r").getChannel(), filter); }
From source file:io.ecarf.core.utils.Utils.java
/** * Get the likely uncompressed size of a Gziped file * @param filename// w w w .j a v a 2 s .com * @return * @throws IOException * @see http://stackoverflow.com/questions/27825927/get-gzipped-file-attributes-like-gzip-l-basically-compression-ratio * @throws FileNotFoundException */ public static long getUncompressedFileSize(String filename) throws FileNotFoundException, IOException { File f = new File(filename); try (RandomAccessFile ra = new RandomAccessFile(f, "r"); FileChannel channel = ra.getChannel()) { MappedByteBuffer fileBuffer = channel.map(MapMode.READ_ONLY, f.length() - 4, 4); fileBuffer.load(); ByteBuffer buf = ByteBuffer.allocate(4); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put(fileBuffer); buf.flip(); //will print the uncompressed size //getInt() reads the 4 bytes as a int // if the file is between 2GB and 4GB // then this will return a negative value //and you'll have to do your own converting to an unsigned int int size = buf.getInt(); if (size < 0) { return FileUtils.ONE_GB + size; } else { return size; } } }
From source file:com.bigdata.dastor.io.SSTableReader.java
private static MappedByteBuffer mmap(String filename, long start, int size) throws IOException { RandomAccessFile raf;//from www. j av a2s . co m try { raf = new RandomAccessFile(filename, "r"); } catch (FileNotFoundException e) { throw new IOError(e); } try { return raf.getChannel().map(FileChannel.MapMode.READ_ONLY, start, size); } finally { raf.close(); } }