List of usage examples for java.io RandomAccessFile seek
public void seek(long pos) throws IOException
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;// w w w . j av a2 s . c o m 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:com.lewa.crazychapter11.MainActivity.java
private void WriteToSdCard(String content) { try {/* w ww .jav a 2 s. c o m*/ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File sdCardDir = Environment.getExternalStorageDirectory(); File targetFile = new File(sdCardDir.getCanonicalPath() + FILE_NAME_SDCARD); Log.i("crazyFile", "WriteToSdCard: sdCardDir=" + sdCardDir + " \n targetFile=" + targetFile); RandomAccessFile raf = new RandomAccessFile(targetFile, "rw"); raf.seek(targetFile.length()); raf.write(content.getBytes()); raf.close(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.kuali.student.git.model.SvnRevisionMapper.java
private long createRevisionEntry(RandomAccessFile dataFile, long endOfDataFileOffset, long revision, List<String> revisionLines) throws IOException { OutputStream revisionMappingStream = null; ByteArrayOutputStream bytesOut; revisionMappingStream = new BZip2CompressorOutputStream(bytesOut = new ByteArrayOutputStream()); PrintWriter pw = new PrintWriter(revisionMappingStream); IOUtils.writeLines(revisionLines, "\n", pw); pw.flush();//from w w w . j a v a 2 s. c o m pw.close(); byte[] data = bytesOut.toByteArray(); dataFile.seek(endOfDataFileOffset); dataFile.write(data); return data.length; }
From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetImpl.java
static private void truncateBlock(File blockFile, File metaFile, long oldlen, long newlen) throws IOException { LOG.info("truncateBlock: blockFile=" + blockFile + ", metaFile=" + metaFile + ", oldlen=" + oldlen + ", newlen=" + newlen); if (newlen == oldlen) { return;/*from w ww .j a va 2s . c o m*/ } if (newlen > oldlen) { throw new IOException( "Cannot truncate block to from oldlen (=" + oldlen + ") to newlen (=" + newlen + ")"); } DataChecksum dcs = BlockMetadataHeader.readHeader(metaFile).getChecksum(); int checksumsize = dcs.getChecksumSize(); int bpc = dcs.getBytesPerChecksum(); long n = (newlen - 1) / bpc + 1; long newmetalen = BlockMetadataHeader.getHeaderSize() + n * checksumsize; long lastchunkoffset = (n - 1) * bpc; int lastchunksize = (int) (newlen - lastchunkoffset); byte[] b = new byte[Math.max(lastchunksize, checksumsize)]; RandomAccessFile blockRAF = new RandomAccessFile(blockFile, "rw"); try { //truncate blockFile blockRAF.setLength(newlen); //read last chunk blockRAF.seek(lastchunkoffset); blockRAF.readFully(b, 0, lastchunksize); } finally { blockRAF.close(); } //compute checksum dcs.update(b, 0, lastchunksize); dcs.writeValue(b, 0, false); //update metaFile RandomAccessFile metaRAF = new RandomAccessFile(metaFile, "rw"); try { metaRAF.setLength(newmetalen); metaRAF.seek(newmetalen - checksumsize); metaRAF.write(b, 0, checksumsize); } finally { metaRAF.close(); } }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Encrypt and write the given stream as a full section. Writes section * header and encrypted data starting at the current file offset. When * finished, file offset is at the end of the entire section. *///from w ww .j av a 2 s.c om private int writeSection(RandomAccessFile f, InputStream in) throws IOException, GeneralSecurityException { final long start = f.getFilePointer(); // Write header; we'll come back later to finalize details final Section section = new Section(); section.write(f); final long dataStart = f.getFilePointer(); mRandom.nextBytes(section.iv); final IvParameterSpec ivSpec = new IvParameterSpec(section.iv); mCipher.init(Cipher.ENCRYPT_MODE, mDataKey, ivSpec); mMac.init(mMacKey); int plainLength = 0; byte[] inbuf = new byte[8192]; byte[] outbuf; int n; while ((n = in.read(inbuf)) != -1) { plainLength += n; outbuf = mCipher.update(inbuf, 0, n); if (outbuf != null) { mMac.update(outbuf); f.write(outbuf); } } outbuf = mCipher.doFinal(); if (outbuf != null) { mMac.update(outbuf); f.write(outbuf); } section.setMac(mMac.doFinal()); final long dataEnd = f.getFilePointer(); section.length = dataEnd - dataStart; // Rewind and update header f.seek(start); section.write(f); f.seek(dataEnd); return plainLength; }
From source file:gate.util.reporting.DocTimeReporter.java
/** * A method for reading the file upside down. * * @param fileToBeRead//from www .j a va2 s . c om * An object of the file to be read. * @param chunkSize * An integer specifying the size of the chunks in which file will be * read. * @return A long value pointing to the start position of the given file * chunk. */ private long tail(File fileToBeRead, int chunkSize) throws BenchmarkReportInputFileFormatException { RandomAccessFile raf = null; try { raf = new RandomAccessFile(fileToBeRead, "r"); Vector<String> lastNlines = new Vector<String>(); int delta = 0; long curPos = 0; curPos = raf.length() - 1; long fromPos; byte[] bytearray; while (true) { fromPos = curPos - chunkSize; if (fromPos <= 0) { raf.seek(0); bytearray = new byte[(int) curPos]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines, fromPos)) { if (fromPos < 0) fromPos = 0; } break; } else { raf.seek(fromPos); bytearray = new byte[chunkSize]; raf.readFully(bytearray); if (parseLinesFromLast(bytearray, lastNlines, fromPos)) { break; } delta = lastNlines.get(lastNlines.size() - 1).length(); lastNlines.remove(lastNlines.size() - 1); curPos = fromPos + delta; } } if (fromPos < 0) throw new BenchmarkReportInputFileFormatException( getBenchmarkFile() + " does not contain a marker named " + getLogicalStart() + " indicating logical start of a run."); return fromPos; } catch (IOException e) { e.printStackTrace(); return -1; } finally { IOUtils.closeQuietly(raf); } }
From source file:org.commoncrawl.service.crawler.CrawlLog.java
/** * seek out next instance of sync bytes in the file input stream * // w w w. ja va 2s . c o m * @param file * @throws IOException */ private static boolean seekToNextSyncBytesPos(byte[] syncBytesBuffer, RandomAccessFile file, long maxFileSize) throws IOException { while (file.getFilePointer() < maxFileSize) { try { // read in a sync.length buffer amount file.read(syncBytesBuffer); int syncLen = SYNC_BYTES_SIZE; // start scan for next sync position ... for (int i = 0; file.getFilePointer() < maxFileSize; i++) { int j = 0; for (; j < syncLen; j++) { if (_sync[j] != syncBytesBuffer[(i + j) % syncLen]) break; } if (j == syncLen) { // found matching sync bytes - reset file pos to before sync bytes file.seek(file.getFilePointer() - SYNC_BYTES_SIZE); // position // before // sync return true; } syncBytesBuffer[i % syncLen] = file.readByte(); } } catch (IOException e) { LOG.warn("IOException at:" + file.getFilePointer() + " Exception:" + CCStringUtils.stringifyException(e)); LOG.warn("Skipping to:" + file.getFilePointer() + 4096); file.seek(file.getFilePointer() + 4096); } } return false; }
From source file:org.commoncrawl.service.crawler.CrawlList.java
private static long readLogFileHeader(RandomAccessFile file, LogFileHeader header) throws IOException { file.seek(0); header.readHeader(file);/* www . ja v a2s. c o m*/ return file.getFilePointer(); }
From source file:org.mitre.mpf.mvc.util.tailer.MpfLogTailer.java
/** * Read new lines.//from ww w . j a va 2s .c o m * * @param reader The file to read * @param maxLines The maximum number of lines to read * @return The number of lines read * @throws IOException if an I/O error occurs. */ private int readLines(RandomAccessFile reader, int maxLines) throws IOException { int numLines = 0; StringBuilder sb = new StringBuilder(); long pos = reader.getFilePointer(); long rePos = pos; // position to re-read byte ch; boolean seenCR = false; while (((ch = (byte) (reader.read())) != -1) && (numLines < maxLines)) { switch (ch) { case '\n': seenCR = false; // swallow CR before LF if (listener.handle(sb.toString())) { numLines++; } sb.setLength(0); rePos = pos + 1; break; case '\r': if (seenCR) { sb.append('\r'); } seenCR = true; break; default: if (seenCR) { seenCR = false; // swallow final CR if (listener.handle(sb.toString())) { numLines++; } sb.setLength(0); rePos = pos + 1; } sb.append((char) ch); // add character, not its ascii value } pos = reader.getFilePointer(); } reader.seek(rePos); // Ensure we can re-read if necessary position = rePos; return numLines; }
From source file:gate.util.reporting.DocTimeReporter.java
/** * Provides the functionality to separate out pipeline specific benchmark * entries in separate temporary benchmark files in a temporary folder in the * current working directory.//from w w w . j a v a 2 s.c om * * @param benchmarkFile * An object of type File representing the input benchmark file. * @param report * A file handle to the report file to be written. * @throws BenchmarkReportFileAccessException * if any error occurs while accessing the input benchmark file or * while splitting it. * @throws BenchmarkReportExecutionException * if the given input benchmark file is modified while generating * the report. */ private void splitBenchmarkFile(File benchmarkFile, File report) throws BenchmarkReportFileAccessException, BenchmarkReportInputFileFormatException { File dir = temporaryDirectory; // Folder already exists; then delete all files in the temporary folder if (dir.isDirectory()) { File files[] = dir.listFiles(); for (int count = 0; count < files.length; count++) { if (!files[count].delete()) { throw new BenchmarkReportFileAccessException( "Could not delete files in the folder \"" + temporaryDirectory + "\""); } } } else if (!dir.mkdir()) { throw new BenchmarkReportFileAccessException( "Could not create temporary folder \"" + temporaryDirectory + "\""); } // delete report2 from the filesystem if (getPrintMedia().equalsIgnoreCase(MEDIA_TEXT)) { deleteFile(new File(report.getAbsolutePath() + ".txt")); } else if (getPrintMedia().equalsIgnoreCase(MEDIA_HTML)) { deleteFile(new File(report.getAbsolutePath() + ".html")); } RandomAccessFile in = null; BufferedWriter out = null; try { String logEntry = ""; long fromPos = 0; // File benchmarkFileName; if (getLogicalStart() != null) { fromPos = tail(benchmarkFile, FILE_CHUNK_SIZE); } in = new RandomAccessFile(benchmarkFile, "r"); if (getLogicalStart() != null) { in.seek(fromPos); } ArrayList<String> startTokens = new ArrayList<String>(); String lastStart = ""; Pattern pattern = Pattern.compile("(\\d+) (\\d+) (.*) (.*) \\{(.*)\\}"); Matcher matcher = null; File benchmarkFileName = null; while ((logEntry = in.readLine()) != null) { matcher = pattern.matcher(logEntry); String startToken = ""; if (logEntry.matches(".*START.*")) { String[] splittedStartEntry = logEntry.split("\\s"); if (splittedStartEntry.length > 2) { startToken = splittedStartEntry[2]; } else { throw new BenchmarkReportInputFileFormatException(getBenchmarkFile() + " is invalid."); } if (startToken.endsWith("Start")) { continue; } if (!startTokens.contains(startToken)) { // create a new file for the new pipeline startTokens.add(startToken); benchmarkFileName = new File(temporaryDirectory, startToken + "_benchmark.txt"); if (!benchmarkFileName.createNewFile()) { throw new BenchmarkReportFileAccessException("Could not create \"" + startToken + "_benchmark.txt" + "\" in directory named \"" + temporaryDirectory + "\""); } out = new BufferedWriter(new FileWriter(benchmarkFileName)); out.write(logEntry); out.newLine(); } } // if a valid benchmark entry then write it to the pipeline specific // file if (matcher != null && matcher.matches() && (validateLogEntry(matcher.group(3), startTokens) || logEntry.matches(".*documentLoaded.*"))) { startToken = matcher.group(3).split("\\.")[0]; if (!(lastStart.equals(startToken))) { if (out != null) { out.close(); } benchmarkFileName = new File(temporaryDirectory, startToken + "_benchmark.txt"); out = new BufferedWriter(new FileWriter(benchmarkFileName, true)); } if (out != null) { out.write(logEntry); out.newLine(); } lastStart = startToken; } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } }