List of usage examples for java.io RandomAccessFile close
public void close() throws IOException
From source file:org.apache.flume.channel.file.TestFileChannelRestart.java
private void doTestCorruptInflights(String name, boolean backup) throws Exception { Map<String, String> overrides = Maps.newHashMap(); overrides.put(FileChannelConfiguration.USE_DUAL_CHECKPOINTS, String.valueOf(backup)); channel = createFileChannel(overrides); channel.start();/* www. j a v a 2 s .c om*/ Assert.assertTrue(channel.isOpen()); final Set<String> in1 = putEvents(channel, "restart-", 10, 100); Assert.assertEquals(100, in1.size()); Executors.newSingleThreadScheduledExecutor().submit(new Runnable() { @Override public void run() { Transaction tx = channel.getTransaction(); Set<String> out1 = takeWithoutCommit(channel, tx, 100); Assert.assertEquals(100, out1.size()); } }); Transaction tx = channel.getTransaction(); Set<String> in2 = putWithoutCommit(channel, tx, "restart", 100); Assert.assertEquals(100, in2.size()); forceCheckpoint(channel); if (backup) { Thread.sleep(2000); } tx.commit(); tx.close(); channel.stop(); File inflight = new File(checkpointDir, name); RandomAccessFile writer = new RandomAccessFile(inflight, "rw"); writer.write(new Random().nextInt()); writer.close(); channel = createFileChannel(overrides); channel.start(); Assert.assertTrue(channel.isOpen()); Assert.assertTrue(!backup || channel.checkpointBackupRestored()); Set<String> out = consumeChannel(channel); in1.addAll(in2); compareInputAndOut(in1, out); }
From source file:hudson.util.TextFile.java
/** * Efficiently reads the last N characters (or shorter, if the whole file is shorter than that.) * * <p>/*from w w w . ja v a 2s . c o m*/ * This method first tries to just read the tail section of the file to get the necessary chars. * To handle multi-byte variable length encoding (such as UTF-8), we read a larger than * necessary chunk. * * <p> * Some multi-byte encoding, such as Shift-JIS (http://en.wikipedia.org/wiki/Shift_JIS) doesn't * allow the first byte and the second byte of a single char to be unambiguously identified, * so it is possible that we end up decoding incorrectly if we start reading in the middle of a multi-byte * character. All the CJK multi-byte encodings that I know of are self-correcting; as they are ASCII-compatible, * any ASCII characters or control characters will bring the decoding back in sync, so the worst * case we just have some garbage in the beginning that needs to be discarded. To accommodate this, * we read additional 1024 bytes. * * <p> * Other encodings, such as UTF-8, are better in that the character boundary is unambiguous, * so there can be at most one garbage char. For dealing with UTF-16 and UTF-32, we read at * 4 bytes boundary (all the constants and multipliers are multiples of 4.) * * <p> * Note that it is possible to construct a contrived input that fools this algorithm, and in this method * we are willing to live with a small possibility of that to avoid reading the whole text. In practice, * such an input is very unlikely. * * <p> * So all in all, this algorithm should work decently, and it works quite efficiently on a large text. */ public @Nonnull String fastTail(int numChars, Charset cs) throws IOException { RandomAccessFile raf = new RandomAccessFile(file, "r"); try { long len = raf.length(); // err on the safe side and assume each char occupies 4 bytes // additional 1024 byte margin is to bring us back in sync in case we started reading from non-char boundary. long pos = Math.max(0, len - (numChars * 4 + 1024)); raf.seek(pos); byte[] tail = new byte[(int) (len - pos)]; raf.readFully(tail); String tails = cs.decode(java.nio.ByteBuffer.wrap(tail)).toString(); return new String(tails.substring(Math.max(0, tails.length() - numChars))); // trim the baggage of substring by allocating a new String } finally { raf.close(); } }
From source file:hudson.FilePathTest.java
private void checkTarUntarRoundTrip(String filePrefix, long fileSize) throws Exception { final File tmpDir = temp.newFolder(filePrefix); final File tempFile = new File(tmpDir, filePrefix + ".log"); RandomAccessFile file = new RandomAccessFile(tempFile, "rw"); final File tarFile = new File(tmpDir, filePrefix + ".tar"); file.setLength(fileSize);// w w w .j ava 2s .c o m assumeTrue(fileSize == file.length()); file.close(); // Compress archive final FilePath tmpDirPath = new FilePath(tmpDir); int tar = tmpDirPath.tar(new FileOutputStream(tarFile), tempFile.getName()); assertEquals("One file should have been compressed", 1, tar); // Decompress FilePath outDir = new FilePath(temp.newFolder(filePrefix + "_out")); final FilePath outFile = outDir.child(tempFile.getName()); tmpDirPath.child(tarFile.getName()).untar(outDir, TarCompression.NONE); assertEquals("Result file after the roundtrip differs from the initial file", new FilePath(tempFile).digest(), outFile.digest()); }
From source file:dk.statsbiblioteket.util.LineReaderTest.java
public void testReadTypes() throws Exception { File temp = createTempFile(); RandomAccessFile raf = new RandomAccessFile(temp, "rw"); writeSample(raf);/*from w w w . j av a 2 s.c o m*/ raf.close(); LineReader lr = new LineReader(temp, "rw"); testSample("LR", lr); lr.close(); temp.createNewFile(); lr = new LineReader(temp, "rw"); writeSample(lr); lr.close(); raf = new RandomAccessFile(temp, "rw"); testSample("RA", raf); raf.close(); }
From source file:com.liferay.portal.util.FileImpl.java
public byte[] getBytes(File file) throws IOException { if ((file == null) || !file.exists()) { return null; }//from w ww . j a va2 s.co m RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); byte[] bytes = new byte[(int) randomAccessFile.length()]; randomAccessFile.readFully(bytes); randomAccessFile.close(); return bytes; }
From source file:org.commoncrawl.service.crawler.CrawlLog.java
public static LogFileHeader readLogFileHeader(File logFileName) throws IOException { LogFileHeader headerOut = new LogFileHeader(); RandomAccessFile file = new RandomAccessFile(logFileName, "r"); try {/* w ww .j a va2s . c o m*/ headerOut = readLogFileHeader(file); } finally { file.close(); } return headerOut; }
From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java
private static void encryptFile(File file, EncryptedFormInformation formInfo) throws IOException, EncryptionException { File encryptedFile = new File(file.getParentFile(), file.getName() + ".enc"); if (encryptedFile.exists() && !encryptedFile.delete()) { throw new IOException( "Cannot overwrite " + encryptedFile.getAbsolutePath() + ". Perhaps the file is locked?"); }/*from w w w.j a va2 s . com*/ // add elementSignatureSource for this file... formInfo.appendFileSignatureSource(file); RandomAccessFile randomAccessFile = null; CipherOutputStream cipherOutputStream = null; try { Cipher c = formInfo.getCipher(); randomAccessFile = new RandomAccessFile(encryptedFile, "rws"); ByteArrayOutputStream encryptedData = new ByteArrayOutputStream(); cipherOutputStream = new CipherOutputStream(encryptedData, c); InputStream fin = new FileInputStream(file); byte[] buffer = new byte[2048]; int len = fin.read(buffer); while (len != -1) { cipherOutputStream.write(buffer, 0, len); len = fin.read(buffer); } fin.close(); cipherOutputStream.flush(); cipherOutputStream.close(); randomAccessFile.write(encryptedData.toByteArray()); Log.i(t, "Encrpyted:" + file.getName() + " -> " + encryptedFile.getName()); } catch (Exception e) { String msg = "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName(); Log.e(t, msg, e); e.printStackTrace(); throw new EncryptionException(msg, e); } finally { IOUtils.closeQuietly(cipherOutputStream); if (randomAccessFile != null) { randomAccessFile.close(); } } }
From source file:org.apache.flume.channel.file.TestFileChannelRestart.java
private void doTestTruncatedCheckpointMeta(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. j a va 2 s. com*/ 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(Serialization.getMetaDataFile(checkpoint), "rw"); writer.setLength(0); 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.csipsimple.service.DownloadLibService.java
private boolean installRemoteLib(RemoteLibInfo lib) { String fileName = lib.getFileName(); File filePath = lib.getFilePath(); File tmp_gz = new File(filePath, fileName + ".gz"); File dest = new File(filePath, fileName); try {/* w w w. j a v a 2 s.c o m*/ if (dest.exists()) { dest.delete(); } RandomAccessFile out = new RandomAccessFile(dest, "rw"); out.seek(0); GZIPInputStream zis = new GZIPInputStream(new FileInputStream(tmp_gz)); int len; byte[] buf = new byte[BUFFER]; while ((len = zis.read(buf)) > 0) { out.write(buf, 0, len); } zis.close(); out.close(); Log.d(THIS_FILE, "Ungzip is in : " + dest.getAbsolutePath()); tmp_gz.delete(); //Update preferences fields with current stack values Editor editor = prefs.edit(); editor.putString(CURRENT_STACK_ID, lib.getId()); editor.putString(CURRENT_STACK_VERSION, lib.getVersion()); editor.putString(CURRENT_STACK_URI, lib.getDownloadUri().toString()); editor.commit(); return true; } catch (IOException e) { Log.e(THIS_FILE, "We failed to install it ", e); } return false; }
From source file:au.org.ala.layers.web.UserDataService.java
private void setImageBlank(HttpServletResponse response) { if (blankImageBytes == null && blankImageObject != null) { synchronized (blankImageObject) { if (blankImageBytes == null) { try { RandomAccessFile raf = new RandomAccessFile( UserDataService.class.getResource("/blank.png").getFile(), "r"); blankImageBytes = new byte[(int) raf.length()]; raf.read(blankImageBytes); raf.close(); } catch (IOException e) { logger.error("error reading default blank tile", e); }/*from w w w . ja v a2s. c om*/ } } } if (blankImageObject != null) { response.setContentType("image/png"); try { ServletOutputStream outStream = response.getOutputStream(); outStream.write(blankImageBytes); outStream.flush(); outStream.close(); } catch (IOException e) { logger.error("error outputting blank tile", e); } } }