List of usage examples for java.io RandomAccessFile seek
public void seek(long pos) throws IOException
From source file:org.mhisoft.wallet.service.AttachmentService.java
/** * abandon the old store and transfer everthing to the wnew store. * The same model for both old and new store. * * @param oldStorefName/*from w w w .j a v a 2 s. co m*/ * @param model * @param encryptor */ protected void compactAttachmentStore(final String oldStorefName, final WalletModel model, final PBEEncryptor encryptor) { String newStoreName = oldStorefName + ".tmp"; File newFile = new File(newStoreName); if (newFile.exists()) { if (!newFile.delete()) { DialogUtils.getInstance().error("Can't delete the tmp file:" + newStoreName); } } FileAccessTable t = new FileAccessTable(); for (WalletItem item : model.getItemsFlatList()) { if (item.getAttachmentEntry() == null) continue; if (item.getAttachmentEntry().getAccessFlag() == FileAccessFlag.None) { //no change , need to transfer to the new file. t.addEntry(item.getAttachmentEntry()); } else if (item.getAttachmentEntry().getAccessFlag() == FileAccessFlag.Merge) { t.addEntry(item.getAttachmentEntry()); } else if (FileAccessFlag.Create == item.getAttachmentEntry().getAccessFlag() || FileAccessFlag.Update == item.getAttachmentEntry().getAccessFlag()) { if (item.getAttachmentEntry() != null) { if (item.getAttachmentEntry().getNewEntry() != null) t.addEntry(item.getNewAttachmentEntry()); else item.getAttachmentEntry(); } } } RandomAccessFile attachmentFileStore = null; if (t.getSize() > 0) { try { attachmentFileStore = new RandomAccessFile(newStoreName, "rw"); attachmentFileStore.seek(0); attachmentFileStore.writeInt(t.getSize()); writeFileEntries(model, true, oldStorefName, 4, attachmentFileStore, t, model.getEncryptorForRead(), encryptor); attachmentFileStore.close(); attachmentFileStore = null; //now do the swap of the store to the new one. new File(oldStorefName).delete(); newFile.renameTo(new File(oldStorefName)); } catch (IOException e) { e.printStackTrace(); DialogUtils.getInstance().error("compactAttachmentStore() failed", e.getMessage()); } finally { if (attachmentFileStore != null) try { attachmentFileStore.close(); } catch (IOException e) { //e.printStackTrace(); } } } else { //need to handle all images are deleted //just remove the old store. new File(oldStorefName).delete(); } }
From source file:com.teletalk.jserver.util.filedb.LowLevelFileDBTest.java
/** * testCorruptData/*from www.j a v a 2 s.c om*/ */ public void testCorruptData() { logger.info("BEGIN testCorruptData."); String fileNameBase = BASE_PATH + "fileDBCorrupt/fileDBCorrupt"; new File(fileNameBase).mkdirs(); try { new File(fileNameBase + ".idx").delete(); new File(fileNameBase + ".dat").delete(); final int allocationUnitSize = 10; final int blockSize = (allocationUnitSize + DefaultDataFile.BLOCK_HEADER_SIZE + DefaultDataFile.BLOCK_FOOTER_SIZE); LowLevelFileDB lowLevelFileDB = new LowLevelFileDB("LowLevelFileDB", fileNameBase, blockSize, 2, 2, LowLevelFileDB.READ_WRITE_MODE); String dataString = "DATA123456"; byte[] data = dataString.getBytes(); lowLevelFileDB.insertItem("key1", data); lowLevelFileDB.insertItem("key2", data); lowLevelFileDB.insertItem("key3", data); lowLevelFileDB.closeFileDB(); byte[] corruptHeader = new byte[DefaultDataFile.BLOCK_HEADER_SIZE]; // Destroy header of first data block RandomAccessFile randomAccessFile = new RandomAccessFile(fileNameBase + ".dat", "rw"); randomAccessFile.seek(DefaultDataFile.DATA_FILE_HEADER_SIZE); randomAccessFile.write(corruptHeader); randomAccessFile.close(); // Destroy header of second index block randomAccessFile = new RandomAccessFile(fileNameBase + ".idx", "rw"); randomAccessFile.seek(DefaultDataFile.DATA_FILE_HEADER_SIZE + lowLevelFileDB.getIndexFileBlockSize()); randomAccessFile.write(corruptHeader); randomAccessFile.close(); // Reopen lowLevelFileDB = new LowLevelFileDB("LowLevelFileDB", fileNameBase, 20, 2, 2, LowLevelFileDB.READ_WRITE_MODE); byte[] readData = lowLevelFileDB.getItem("key1"); if (readData != null) super.fail("Item with key 'key1' shouldn't exist!"); readData = lowLevelFileDB.getItem("key2"); if (readData != null) super.fail("Item with key 'key2' shouldn't exist!"); readData = lowLevelFileDB.getItem("key3"); if (readData == null) super.fail("Item with key 'key3' wasn't found!"); if (!dataString.equals(new String(readData))) super.fail("Data for item with key 'key3' was invalid!"); lowLevelFileDB.closeFileDB(); FileDeletor.delete("fileDBCorrupt"); new File(fileNameBase + ".idx").delete(); new File(fileNameBase + ".dat").delete(); } catch (Exception e) { e.printStackTrace(); super.fail("Error - " + e); } logger.info("END testCorruptData."); }
From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java
public boolean resumeImages(String msgSubject) { File file = null;// w w w . j a va2 s . c o m long fileLength; try { String filename = "", num = ""; URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); num = getNumber(msgSubject); filename = getTimestamp(msgSubject); file = new File(fileDir + "/" + getNumber(msgSubject) + "/Recieved", filename); if (!file.exists()) { file.createNewFile(); } FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = connection.getInputStream(); int totalSize = connection.getContentLength(); Long downloadedSize = (long) 0; byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize); } fileOutput.close(); Log.d("downloadedSize", downloadedSize + " @"); if (downloadedSize == totalSize) { downloadedimageuri = file.getAbsolutePath(); return true; } if (file.exists()) { connection.setAllowUserInteraction(true); connection.setRequestProperty("Range", "bytes=" + file.length() + "-"); } connection.setConnectTimeout(14000); connection.setReadTimeout(20000); connection.connect(); if (connection.getResponseCode() / 100 != 2) throw new Exception("Invalid response code!"); else { String connectionField = connection.getHeaderField("content-range"); if (connectionField != null) { String[] connectionRanges = connectionField.substring("bytes=".length()).split("-"); downloadedSize = Long.valueOf(connectionRanges[0]); } if (connectionField == null && file.exists()) file.delete(); fileLength = connection.getContentLength() + downloadedSize; BufferedInputStream input = new BufferedInputStream(connection.getInputStream()); RandomAccessFile output = new RandomAccessFile(file, "rw"); output.seek(downloadedSize); byte data[] = new byte[1024]; int count = 0; int __progress = 0; while ((count = input.read(data, 0, 1024)) != -1 && __progress != 100) { downloadedSize += count; output.write(data, 0, count); __progress = (int) ((downloadedSize * 100) / fileLength); } output.close(); input.close(); } } catch (Exception e) { e.printStackTrace(); return false; } return false; }
From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java
private boolean updateINIOnJDKUpgrade(String javaHome) { logger.debug("Updating INI file if JDK path is updated"); RandomAccessFile file = null; boolean isUpdated = false; try {/*from w ww . j av a 2 s . c o m*/ file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw"); byte[] text = new byte[(int) file.length()]; while (file.getFilePointer() != file.length()) { if (StringUtils.equals(file.readLine(), "-vm")) { String currentLine = file.readLine(); if (StringUtils.equals(currentLine, javaHome)) { logger.debug("JAVA_HOME and -vm in configuration file are same"); } else { logger.debug( "JAVA_HOME and -vm in configuration file are different. Updating configuration file with JAVA_HOME"); file.seek(0); file.readFully(text); file.seek(0); updateData(text, javaHome, currentLine, file); isUpdated = true; } break; } } } catch (IOException ioException) { logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException); } finally { try { if (file != null) { file.close(); } } catch (IOException ioException) { logger.error("IOException occurred while closing " + HYDROGRAPH_INI + " file", ioException); } } return isUpdated; }
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);//from ww w . j a v a 2s . c o m 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:com.louding.frame.http.download.FileEntityHandler.java
public File handleEntity(HttpEntity entity, DownloadProgress callback, File save, boolean isResume) throws IOException { long current = 0; RandomAccessFile file = new RandomAccessFile(save, "rw"); if (isResume) { current = file.length();/*from w w w .jav a2 s . c o m*/ } InputStream input = entity.getContent(); long count = entity.getContentLength() + current; if (mStop) { FileUtils.closeIO(file); return save; } // ??????? /** * <br> * current = input.skip(current); <br> * file.seek(current); <br> * ?JDKInputstream.skip(long i)i<br> * ? n ??????? */ file.seek(input.skip(current)); int readLen = 0; byte[] buffer = new byte[1024]; while ((readLen = input.read(buffer, 0, 1024)) != -1) { if (mStop) { break; } else { file.write(buffer, 0, readLen); current += readLen; callback.onProgress(count, current); } } callback.onProgress(count, current); if (mStop && current < count) { // ? FileUtils.closeIO(file); throw new IOException("user stop download thread"); } FileUtils.closeIO(file); return save; }
From source file:org.apache.flume.channel.file.TestFlumeEventQueue.java
@Test(expected = BadCheckpointException.class) public void testCorruptInflightPuts() throws Exception { RandomAccessFile inflight = null; try {//from w w w . j av a2 s.c om queue = new FlumeEventQueue(backingStore, backingStoreSupplier.getInflightTakes(), backingStoreSupplier.getInflightPuts()); long txnID1 = new Random().nextInt(Integer.MAX_VALUE - 1); long txnID2 = txnID1 + 1; queue.addWithoutCommit(new FlumeEventPointer(1, 1), txnID1); queue.addWithoutCommit(new FlumeEventPointer(2, 1), txnID1); queue.addWithoutCommit(new FlumeEventPointer(2, 2), txnID2); queue.checkpoint(true); TimeUnit.SECONDS.sleep(3L); inflight = new RandomAccessFile(backingStoreSupplier.getInflightPuts(), "rw"); inflight.seek(0); inflight.writeInt(new Random().nextInt()); queue = new FlumeEventQueue(backingStore, backingStoreSupplier.getInflightTakes(), backingStoreSupplier.getInflightPuts()); SetMultimap<Long, Long> deserializedMap = queue.deserializeInflightPuts(); Assert.assertTrue(deserializedMap.get(txnID1).contains(new FlumeEventPointer(1, 1).toLong())); Assert.assertTrue(deserializedMap.get(txnID1).contains(new FlumeEventPointer(2, 1).toLong())); Assert.assertTrue(deserializedMap.get(txnID2).contains(new FlumeEventPointer(2, 2).toLong())); } finally { inflight.close(); } }
From source file:org.apache.flume.channel.file.TestFlumeEventQueue.java
@Test(expected = BadCheckpointException.class) public void testCorruptInflightTakes() throws Exception { RandomAccessFile inflight = null; try {//from w w w . java 2s . co m queue = new FlumeEventQueue(backingStore, backingStoreSupplier.getInflightTakes(), backingStoreSupplier.getInflightPuts()); long txnID1 = new Random().nextInt(Integer.MAX_VALUE - 1); long txnID2 = txnID1 + 1; queue.addWithoutCommit(new FlumeEventPointer(1, 1), txnID1); queue.addWithoutCommit(new FlumeEventPointer(2, 1), txnID1); queue.addWithoutCommit(new FlumeEventPointer(2, 2), txnID2); queue.checkpoint(true); TimeUnit.SECONDS.sleep(3L); inflight = new RandomAccessFile(backingStoreSupplier.getInflightTakes(), "rw"); inflight.seek(0); inflight.writeInt(new Random().nextInt()); queue = new FlumeEventQueue(backingStore, backingStoreSupplier.getInflightTakes(), backingStoreSupplier.getInflightPuts()); SetMultimap<Long, Long> deserializedMap = queue.deserializeInflightTakes(); Assert.assertTrue(deserializedMap.get(txnID1).contains(new FlumeEventPointer(1, 1).toLong())); Assert.assertTrue(deserializedMap.get(txnID1).contains(new FlumeEventPointer(2, 1).toLong())); Assert.assertTrue(deserializedMap.get(txnID2).contains(new FlumeEventPointer(2, 2).toLong())); } finally { inflight.close(); } }
From source file:org.commoncrawl.service.crawler.CrawlLog.java
private static void updateLogFileHeader(File logFileName, LogFileHeader header, long addedRecordCount) throws IOException { RandomAccessFile file = new RandomAccessFile(logFileName, "rw"); try {/*from ww w . j a va2 s. c o m*/ // update cached header ... header._fileSize = file.getChannel().size(); header._itemCount += addedRecordCount; // set the position at zero .. file.seek(0); // and write header to disk ... header.writeHeader(file); } finally { // major bottle neck.. // file.getFD().sync(); file.close(); } }
From source file:com.landenlabs.all_devtool.ConsoleFragment.java
/** * Gets total system cpu usage (not just this app) * @return//from w w w .j av a 2 s . c o m */ private float getCpuUsage() { try { RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r"); String load = reader.readLine(); String[] toks = load.split(" "); long idle1 = Long.parseLong(toks[5]); long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); try { Thread.sleep(360); } catch (Exception e) { } reader.seek(0); load = reader.readLine(); reader.close(); toks = load.split(" "); long idle2 = Long.parseLong(toks[5]); long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); return (float) (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1)); } catch (IOException ex) { ex.printStackTrace(); } return 0; }