List of usage examples for java.io RandomAccessFile close
public void close() throws IOException
From source file:au.org.ala.layers.grid.GridCacheBuilder.java
private static void writeGroupGRI(File file, ArrayList<Grid> group) { Grid g = group.get(0);//w w w . j a va 2 s .co m RandomAccessFile[] raf = new RandomAccessFile[group.size()]; RandomAccessFile output = null; try { output = new RandomAccessFile(file, "rw"); for (int i = 0; i < group.size(); i++) { raf[i] = new RandomAccessFile(group.get(i).filename + ".gri", "r"); } int length = g.ncols * g.nrows; int size = 4; byte[] b = new byte[size * group.size() * g.ncols]; float noDataValue = Float.MAX_VALUE * -1; byte[] bi = new byte[g.ncols * 8]; float[][] rows = new float[group.size()][g.ncols]; for (int i = 0; i < g.nrows; i++) { //read for (int j = 0; j < raf.length; j++) { nextRowOfFloats(rows[j], group.get(j).datatype, group.get(j).byteorderLSB, g.ncols, raf[j], bi, (float) g.nodatavalue); } //write ByteBuffer bb = ByteBuffer.wrap(b); bb.order(ByteOrder.LITTLE_ENDIAN); for (int k = 0; k < g.ncols; k++) { for (int j = 0; j < raf.length; j++) { //float f = getNextValue(raf[j], group.get(j)); float f = rows[j][k]; if (Float.isNaN(f)) { bb.putFloat(noDataValue); } else { bb.putFloat(f); } } } output.write(b); } } catch (IOException e) { logger.error(e.getMessage(), e); } finally { if (output != null) { try { output.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } for (int i = 0; i < raf.length; i++) { if (raf[i] != null) { try { raf[i].close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } } }
From source file:org.apache.flume.channel.file.TestFileChannelRestart.java
private void doTestIncompleteCheckpoint(boolean backup) throws Exception { Map<String, String> overrides = Maps.newHashMap(); overrides.put(FileChannelConfiguration.USE_DUAL_CHECKPOINTS, String.valueOf(backup)); channel = createFileChannel(overrides); channel.start();//from w w w . java 2s .c om Assert.assertTrue(channel.isOpen()); Set<String> in = putEvents(channel, "restart", 10, 100); Assert.assertEquals(100, in.size()); forceCheckpoint(channel); if (backup) { Thread.sleep(2000); } channel.stop(); File checkpoint = new File(checkpointDir, "checkpoint"); RandomAccessFile writer = new RandomAccessFile(checkpoint, "rw"); writer.seek(EventQueueBackingStoreFile.INDEX_CHECKPOINT_MARKER * Serialization.SIZE_OF_LONG); writer.writeLong(EventQueueBackingStoreFile.CHECKPOINT_INCOMPLETE); writer.getFD().sync(); writer.close(); channel = createFileChannel(overrides); channel.start(); Assert.assertTrue(channel.isOpen()); Assert.assertTrue(!backup || channel.checkpointBackupRestored()); Set<String> out = consumeChannel(channel); compareInputAndOut(in, out); }
From source file:com.android.strictmodetest.StrictModeActivity.java
private void fileReadLoop() { RandomAccessFile raf = null; File filename = getFileStreamPath("test.dat"); try {/*from w w w. j a va 2 s . c o m*/ long sumNanos = 0; byte[] buf = new byte[512]; //raf = new RandomAccessFile(filename, "rw"); //raf.write(buf); //raf.close(); //raf = null; // The data's almost certainly cached -- it's not clear what we're testing here raf = new RandomAccessFile(filename, "r"); raf.seek(0); raf.read(buf); } catch (IOException e) { Log.e(TAG, "File read failed", e); } finally { try { if (raf != null) raf.close(); } catch (IOException e) { } } }
From source file:org.apache.james.mailrepository.file.MBoxMailRepository.java
/** * @see org.apache.james.mailrepository.api.MailRepository#store(Mail) *//*from w w w .ja v a 2 s .c om*/ public void store(Mail mc) { if ((getLogger().isDebugEnabled())) { String logBuffer = this.getClass().getName() + " Will store message to file " + mboxFile; getLogger().debug(logBuffer); } this.mList = null; // Now make up the from header String fromHeader = null; String message = null; try { message = getRawMessage(mc.getMessage()); // check for nullsender if (mc.getMessage().getFrom() == null) { fromHeader = "From " + dy.format(Calendar.getInstance().getTime()); } else { fromHeader = "From " + mc.getMessage().getFrom()[0] + " " + dy.format(Calendar.getInstance().getTime()); } } catch (IOException e) { getLogger().error("Unable to parse mime message for " + mboxFile, e); } catch (MessagingException e) { getLogger().error("Unable to parse mime message for " + mboxFile, e); } // And save only the new stuff to disk RandomAccessFile saveFile; try { saveFile = new RandomAccessFile(mboxFile, "rw"); saveFile.seek(saveFile.length()); // Move to the end saveFile.writeBytes((fromHeader + "\n")); saveFile.writeBytes((message + "\n")); saveFile.close(); } catch (FileNotFoundException e) { getLogger().error("Unable to save(open) file (File not found) " + mboxFile, e); } catch (IOException e) { getLogger().error("Unable to write file (General I/O problem) " + mboxFile, e); } }
From source file:jazsync.UploadTests.java
/** * Sets the fields of an Upload object and tests whether the {@link Upload#getInputStream()} * returns the upload data in the expected format. * //w w w . j a v a 2s. c om * @throws IOException */ @Test public void testGetInputStream() throws IOException { Upload um = new Upload(); um.setVersion("testVersion"); um.setBlocksize(1024); um.setFilelength(32768); um.setSha1("sha1checksum"); File testFile = File.createTempFile("Upload", "Test"); RandomAccessFile randAccess = new RandomAccessFile(testFile, "rw"); String inString = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXABCDEYZXXXXX"; randAccess.write(inString.getBytes("US-ASCII")); ByteRangeWriter dataRanges = new ByteRangeWriter(16384); dataRanges.add(new Range(45, 50), randAccess); dataRanges.add(new Range(51, 52), randAccess); um.setDataStream(dataRanges.getInputStream()); RelocWriter relocRanges = new RelocWriter(16384); relocRanges.add(new RelocateRange(new Range(2, 6), 123)); relocRanges.add(new RelocateRange(new Range(8, 98), 987)); um.setRelocStream(relocRanges.getInputStream()); InputStream uploadIn = um.getInputStream(); String actString = IOUtils.toString(uploadIn, Upload.CHARSET); String expString = version + filelength + blocksize + sha1 + relocString + rangeString; uploadIn.close(); randAccess.close(); System.out.println(actString); Assert.assertEquals(expString, actString); }
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 ww . j a v a 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:at.tuwien.minimee.util.TopParser.java
/** * The process ID is in the last line of the file and looks like follows: * monitored_pid= 6738 //w w w . j a v a 2 s. c om * * @param input * @return * @throws Exception */ private Integer findPid() throws Exception { Integer pid = new Integer(0); // we open the file RandomAccessFile f = new RandomAccessFile(file, "r"); try { long size = f.length(); f.seek(size - 2); // we search the file reverse for '=' byte[] b = new byte[1]; for (long i = size - 2; i >= 0; i--) { f.seek(i); f.read(b); if (b[0] == '=') { break; } } String line = f.readLine().trim(); pid = new Integer(line); } finally { // this is important, RandomAccessFile doesn't close the file handle by default! // if close isn't called, you'll get very soon 'too many open files' f.close(); } return pid; }
From source file:com.yifanlu.PSXperiaTool.PSXperiaTool.java
private void patchGame() throws IOException { /*/* www.java2 s .co m*/ * Custom patch format (config/game-patch.bin) is as follows: * 0x8 byte little endian: Address in game image to start patching * 0x8 byte little endian: Length of patch * If there are more patches, repeat after reading the length of patch * Note that all games will be patched the same way, so if a game is broken before patching, it will still be broken! */ nextStep("Patching game."); File gamePatch = new File(mTempDir, "/config/game-patch.bin"); if (!gamePatch.exists()) return; Logger.info("Making a copy of game."); File tempGame = new File(mTempDir, "game.iso"); FileUtils.copyFile(mInputFile, tempGame); RandomAccessFile game = new RandomAccessFile(tempGame, "rw"); InputStream patch = new FileInputStream(gamePatch); while (true) { byte[] rawPatchAddr = new byte[8]; byte[] rawPatchLen = new byte[8]; if (patch.read(rawPatchAddr) + patch.read(rawPatchLen) < rawPatchAddr.length + rawPatchLen.length) break; ByteBuffer bb = ByteBuffer.wrap(rawPatchAddr); bb.order(ByteOrder.LITTLE_ENDIAN); long patchAddr = bb.getLong(); bb = ByteBuffer.wrap(rawPatchLen); bb.order(ByteOrder.LITTLE_ENDIAN); long patchLen = bb.getLong(); game.seek(patchAddr); while (patchLen-- > 0) { game.write(patch.read()); } } mInputFile = tempGame; game.close(); patch.close(); Logger.debug("Done patching game."); }
From source file:org.andrewberman.sync.PDFDownloader.java
void retrievePDFsFromHTML() throws Exception { if (!baseDir.exists() || !baseDir.canWrite() || !baseDir.isDirectory()) { throw new Exception("Error: Destination is read-only or does not exist."); }/*from ww w. j a v a 2 s . c o m*/ String base = baseDir.getCanonicalPath() + sep; syncBibTex(); do { Thread.sleep(InheritMe.BETWEEN_PDF_DOWNLOADS_SLEEP_TIME); getArticleInfo(); /* * First thing's first, create folders and insert the URL links if necessary. */ if (subTags) { status("Creating folders and links..."); createTagFoldersAndLinks(tagSet); status("Folders and links created!"); // Thread.sleep(PAUSE_TIME/10); } List<CiteULikeReference> articlesWithoutPDFs = this.getArticlesWithoutPDFs(this.refs); List<CiteULikeReference> articlesWithPDFs = new ArrayList<CiteULikeReference>(); articlesWithPDFs.addAll(this.refs); articlesWithPDFs.removeAll(articlesWithoutPDFs); itemMax = articlesWithPDFs.size(); itemNum = 0; int i = -1; for (CiteULikeReference ref : articlesWithPDFs) { System.out.println(ref.userfiles); itemNum++; i++; waitOrExit(); setArticleLink("Current article ID: " + ref.article_id, ref.href); try { waitOrExit(); // Grab the article page's text to get the date. Date remote = null; // if (this.uploadNewer) { String articleContent = get(ref.href); remote = getStampFromArticlePage(articleContent); System.out.println("Remote timestamp: " + remote); // } status("Checking for existing file..."); for (String fileName : ref.userfiles.keySet()) { waitOrExit(); String fullPath = ref.userfiles.get(fileName); System.out.println(fileName + " -> " + fullPath); /* * Try and put the year first. */ String[] bits = fileName.split("_"); String yearS = ""; String otherFilename = ""; String targetFilename = ""; if (bits.length == 3) { String flipped = bits[1] + "_" + bits[0] + "_" + bits[2]; if (flipFilename) { otherFilename = fileName; targetFilename = flipped; } else { targetFilename = fileName; otherFilename = flipped; } if (subYears) { yearS = String.valueOf(bits[1]); } } else { targetFilename = fileName; otherFilename = fileName; } /* * If we're organized by tags, add a destination file for each of this PDf's tags. * If not, then just add the one outputFile to the outputFiles array. */ ArrayList<File> outputFiles = new ArrayList<File>(); ArrayList<File> maybeNewFiles = new ArrayList<File>(); File altFile = null; File myFile = null; // Keep track of the newest file and its timestamp. File newestFile = null; long newestStamp = 0; if (subTags && ref.getTags().size() > 0) { for (String tag : ref.getTags()) { if (tag.equalsIgnoreCase("no-tag")) tag = ""; String curDir = base + tag + sep; curDir += yearS; myFile = new File(curDir + sep + targetFilename); altFile = new File(curDir + sep + otherFilename); if (myFile.exists()) { newestFile = returnNewer(newestFile, myFile); } else if (altFile.exists()) { try { altFile.renameTo(myFile); } catch (Exception e) { e.printStackTrace(); } // outputFiles.add(myFile); } else { outputFiles.add(myFile); } } } else { myFile = new File(base + yearS + sep + targetFilename); altFile = new File(base + yearS + sep + otherFilename); maybeNewFiles.add(myFile); maybeNewFiles.add(altFile); if (myFile.exists()) { newestFile = returnNewer(newestFile, myFile); } else if (altFile.exists()) { try { altFile.renameTo(myFile); } catch (Exception e) { e.printStackTrace(); System.exit(0); } // outputFiles.add(myFile); } else { outputFiles.add(myFile); } } // If we have a newest file, check against the server to see if it's much newer. if (newestFile != null && remote != null) { Date local = new Date(newestFile.lastModified()); long lT = local.getTime(); long rT = remote.getTime(); if (lT - rT > (1000) * (60) * (1)) // Fudge factor of 1 minute. { if (uploadNewer) { System.err.println("Local file is newer than remote! Uploading..."); status("Local file was modified! Uploading..."); // OK. Since CiteULike now uses hashing to evaluate the identity of files, we have to first delete // the existing attachment with this filename. String url = this.BASE_URL + "personal_pdf_delete?"; url += "username=" + this.username; url += "&article_id=" + ref.article_id; // Parse the userfile_id from the filename: String userFileId = ref.userfileIds.get(fileName); url += "&userfile_id=" + userFileId; System.out.println(url); get(url); uploadPDF(ref.article_id, newestFile); // Re-collect the timestamp, and re-stamp the local file. This is done so they match after re-uploading. String newContent = get(ref.href); Date remote2 = getStampFromArticlePage(newContent); newestFile.setLastModified(remote2.getTime()); } } } if (outputFiles.size() == 0) { status("Already up-to-date!"); utd++; continue; } Thread.sleep(200); /* * Download the PDF to the first file. */ waitOrExit(); status("Downloading..."); File f = outputFiles.remove(0); try { String fileUrl = this.BASE_URL + fullPath; this.retriesLeft = 2; downloadURLToFile(fileUrl, f); if (remote != null) f.setLastModified(remote.getTime()); } catch (Exception e) { e.printStackTrace(); f.delete(); throw e; } dl++; /* * Go through rest of tags, and copy file accordingly. * NOTE: This is only entered if this file needs to be copied over locally. */ for (int j = 0; j < outputFiles.size(); j++) { status("Copying PDF..."); File f2 = outputFiles.get(j); if (f2.exists()) { if (f2.lastModified() > newestStamp) { newestFile = f2; newestStamp = f2.lastModified(); } continue; } f2.getParentFile().mkdirs(); f2.createNewFile(); RandomAccessFile in = new RandomAccessFile(f, "r"); RandomAccessFile out = new RandomAccessFile(f2, "rw"); byte[] b = new byte[(int) in.length()]; in.readFully(b); out.write(b); in.close(); out.close(); f2.setLastModified(remote.getTime()); } } } catch (Exception e) { err++; e.printStackTrace(); status("Failed. See the Java console for more info."); Thread.sleep(PAUSE_TIME / 2); continue; } } } while (this.refs.size() > 0); this.pageNum = 0; status("Finished. " + dl + " new, " + utd + " up-to-date and " + err + " failed."); out.println("Done!"); }
From source file:com.zimbra.cs.redolog.util.RedoLogVerify.java
public boolean scanLog(File logfile) throws IOException { boolean good = false; FileLogReader logReader = new FileLogReader(logfile, false); logReader.open();// w w w. ja v a2s. c o m if (!mParams.quiet) { FileHeader header = logReader.getHeader(); mOut.println("HEADER"); mOut.println("------"); mOut.print(header); mOut.println("------"); } boolean hasMailboxIdsFilter = !mParams.mboxIds.isEmpty(); RedoableOp op = null; long lastPosition = 0; long lastOpStartOffset = 0; try { while ((op = logReader.getNextOp()) != null) { lastOpStartOffset = logReader.getLastOpStartOffset(); lastPosition = logReader.position(); if (hasMailboxIdsFilter) { int mboxId = op.getMailboxId(); if (op instanceof StoreIncomingBlob) { List<Integer> list = ((StoreIncomingBlob) op).getMailboxIdList(); if (list != null) { boolean match = false; for (Integer mid : list) { if (mParams.mboxIds.contains(mid)) { match = true; break; } } if (!match) continue; } // If list==null, it's a store incoming blob op targeted at unknown set of mailboxes. // It applies to our filtered mailboxes. } else if (!mParams.mboxIds.contains(mboxId)) { continue; } } if (!mParams.quiet) { printOp(mOut, op, mParams.hideOffset, lastOpStartOffset, lastPosition - lastOpStartOffset); if (mParams.showBlob) { InputStream dataStream = op.getAdditionalDataStream(); if (dataStream != null) { mOut.println("<START OF BLOB>"); ByteUtil.copy(dataStream, true, mOut, false); mOut.println(); mOut.println("<END OF BLOB>"); } } } } good = true; } catch (IOException e) { // The IOException could be a real I/O problem or it could mean // there was a server crash previously and there were half-written // log entries. mOut.println(); mOut.printf("Error while parsing data starting at offset 0x%08x", lastPosition); mOut.println(); long size = logReader.getSize(); long diff = size - lastPosition; mOut.printf("%d bytes remaining in the file", diff); mOut.println(); mOut.println(); if (op != null) { mOut.println("Last suceessfully parsed redo op:"); printOp(mOut, op, false, lastOpStartOffset, lastPosition - lastOpStartOffset); mOut.println(); } // hexdump data around the bad bytes int bytesPerLine = 16; int linesBefore = 10; int linesAfter = 10; long startPos = Math.max(lastPosition - (lastPosition % bytesPerLine) - linesBefore * bytesPerLine, 0); int count = (int) Math.min((linesBefore + linesAfter + 1) * bytesPerLine, lastPosition - startPos + diff); RandomAccessFile raf = null; try { raf = new RandomAccessFile(logfile, "r"); raf.seek(startPos); byte buf[] = new byte[count]; raf.read(buf, 0, count); mOut.printf("Data near error offset %08x:", lastPosition); mOut.println(); hexdump(mOut, buf, 0, count, startPos, lastPosition); mOut.println(); } catch (IOException eh) { mOut.println("Error opening log file " + logfile.getAbsolutePath() + " for hexdump"); eh.printStackTrace(mOut); } finally { if (raf != null) raf.close(); } throw e; } finally { logReader.close(); } return good; }