List of usage examples for java.io RandomAccessFile seek
public void seek(long pos) throws IOException
From source file:com.limegroup.gnutella.metadata.MP3DataEditor.java
public int commitMetaData(String filename) { if (LOG.isDebugEnabled()) LOG.debug("committing mp3 file"); if (!LimeXMLUtils.isMP3File(filename)) return LimeXMLReplyCollection.INCORRECT_FILETYPE; File f = null;// w w w . jav a 2 s.c o m RandomAccessFile file = null; try { try { f = new File(filename); FileUtils.setWriteable(f); file = new RandomAccessFile(f, "rw"); } catch (IOException e) { return LimeXMLReplyCollection.FILE_DEFECTIVE; } long length = 0; try { length = file.length(); if (length < 128) //could not write - file too small return LimeXMLReplyCollection.FILE_DEFECTIVE; file.seek(length - 128); } catch (IOException ee) { return LimeXMLReplyCollection.RW_ERROR; } //1. Try to write out the ID3v2 data first int ret = -1; try { ret = writeID3V2DataToDisk(f); } catch (IOException iox) { return LimeXMLReplyCollection.RW_ERROR; } catch (ID3v2Exception e) { //catches both ID3v2 related exceptions ret = writeID3V1DataToDisk(file); } return ret; } finally { if (file != null) { try { file.close(); } catch (IOException ignored) { } } } }
From source file:translator.logic.AllVendorAnnotationTranslator.java
/** * Reads an edf file and return an array containing start date, time and duration(in seconds) * @param edfFile edf to be read// w w w .java2 s. co m * @return the string array containing start date, time and duration(in seconds) */ public String[] readEDF(String edfFile) { String[] startDate = new String[2]; @SuppressWarnings("unused") SimpleDateFormat df = new SimpleDateFormat("mm.dd.yyyy hh.mm.ss"); try { RandomAccessFile edf = new RandomAccessFile(new File(edfFile), "r"); edf.seek(168); char[] date = new char[8]; for (int i = 0; i < 8; i++) { date[i] = (char) edf.readByte(); } // edf.read(date); char[] time = new char[8]; for (int i = 0; i < 8; i++) { time[i] = (char) edf.readByte(); } edf.seek(236); char[] numRec = new char[8]; for (int i = 0; i < 8; i++) { numRec[i] = (char) edf.readByte(); //System.out.println(dur[i]); } char[] durRec = new char[8]; for (int i = 0; i < 8; i++) { durRec[i] = (char) edf.readByte(); //System.out.println(dur[i]); } // long numRec = edf.readLong(); // long durRec = edf.readLong(); long duration = Long.parseLong(String.valueOf(durRec).trim()) * Long.parseLong(String.valueOf(numRec).trim()); // long duration = 0; // edf.read(time); startDate[0] = String.valueOf(date) + " " + String.valueOf(time); startDate[1] = String.valueOf(duration); edf.close(); } catch (Exception e) { e.printStackTrace(); StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); log(errors.toString()); } return startDate; }
From source file:org.opencb.cellbase.lib.db.VariantAnnotationCalculatorTest.java
private void skipVepFileHeader(RandomAccessFile raf) throws IOException { String line;//w ww.java 2s . c o m long pos; do { pos = raf.getFilePointer(); line = raf.readLine(); } while (line.startsWith("#")); raf.seek(pos); }
From source file:org.sbs.util.download.MultiThreadDownload.java
/** * // w w w .j a va2 s . c om * @param url * @param path * @param fileName * @return * @throws DownLoadException */ @SuppressWarnings("unchecked") public File downLoad(final URL url, String path, String fileName) throws DownLoadException { // ?? this.downLen = -1; this.contentLen = 0; this.date = new Date(); this.finished = false; try { URLConnection con = url.openConnection(); //? this.contentLen = con.getContentLength(); //?? if (StringUtils.isBlank(fileName)) { fileName = StringUtils.substringAfterLast(url.getPath(), "/"); } // File _path = new File(path); if (!_path.exists()) { _path.mkdirs(); } final File file = new File(path + File.separator + fileName); if (file.exists()) file.delete(); if (this.threadNum == 0 && this.blockSize > 0) { this.threadNum = (int) (contentLen / blockSize); if (this.threadNum == 0) { this.threadNum = 1; } } long subLen = contentLen / threadNum; List<Future<DownLoadBean>> result = Lists.newArrayList(); for (int i = 0; i < threadNum; i++) { final int pos = (int) (i * subLen); final int end = (int) ((i + 1) * subLen) - 1; final int current = pos; Future<DownLoadBean> f = (Future<DownLoadBean>) pool.submit(new Callable<DownLoadBean>() { int $pos = pos; int $end = end; int $current = current; @Override public DownLoadBean call() throws Exception { //buff BufferedInputStream bis = null; RandomAccessFile fos = null; byte[] buf = new byte[BUFFER_SIZE]; URLConnection con = null; try { con = url.openConnection(); con.setAllowUserInteraction(true); //???startPosendPos con.setRequestProperty("Range", "bytes=" + $pos + "-" + $end); fos = new RandomAccessFile(file, "rw"); //startPos fos.seek($pos); //????curPos???endPos //endPos? bis = new BufferedInputStream(con.getInputStream()); while ($current < $end) { int len = bis.read(buf, 0, BUFFER_SIZE); if (len == -1) { break; } fos.write(buf, 0, len); $current = $current + len; if ($current - 1 > $end) { throw new DownLoadException( "????"); } addLen(len); } bis.close(); fos.close(); } catch (IOException ex) { /* ????? StringBuffer sb = new StringBuffer(); sb.append($pos).append("\t").append($current).append("\t").append($end).append("\n"); FileUtils.write(new File(file.getAbsolutePath()+".pos"), sb, true); */ throw new RuntimeException(ex); } log.debug(this.hashCode() + ":??[" + $pos + "," + $end + "]"); return new DownLoadBean($pos, $end, $current); } }); result.add(f); } Long resultTotal = 0L; for (Future<DownLoadBean> f : result) { DownLoadBean dInfo = f.get(); resultTotal += dInfo.getCurrent() - dInfo.getPos(); } // ? if (contentLen > resultTotal + 1) { // ??? FileUtils.write(new File(down_error_log_file), url.toString() + "\n", true); throw new DownLoadException("?"); } else { finished = true; return file; } } catch (IOException | InterruptedException | ExecutionException e) { // try { FileUtils.write(new File(down_error_log_file), url.toString() + "\n", true); } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); } return null; }
From source file:dk.statsbiblioteket.util.LineReaderTest.java
public void dumpSequentialRA() throws Exception { RandomAccessFile ra = new RandomAccessFile(logfile, "r"); for (int i = 0; i < LINES; i++) { ra.readLine();// w w w . ja v a2s . c o m } Profiler profiler = new Profiler(); profiler.setExpectedTotal(SEQUENTIAL_RUNS); for (int i = 0; i < SEQUENTIAL_RUNS; i++) { ra.seek(0); for (int j = 0; j < LINES; j++) { ra.readLine(); } profiler.beat(); } System.out.println("Performed " + SEQUENTIAL_RUNS + " full RA reads at " + Math.round(profiler.getBps(false)) + " reads/second"); }
From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.fragments.EventGeneratorFragment.java
private float readCPUUsage() { try {//w w w.java 2s .c o m 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; }
From source file:org.apache.hadoop.hdfs.server.namenode.NNStorage.java
@Override // Storage public boolean isConversionNeeded(StorageDirectory sd) throws IOException { if (disablePreUpgradableLayoutCheck) { return false; }//from w w w .j av a2 s. co m File oldImageDir = new File(sd.getRoot(), "image"); if (!oldImageDir.exists()) { return false; } // check the layout version inside the image file File oldF = new File(oldImageDir, "fsimage"); RandomAccessFile oldFile = new RandomAccessFile(oldF, "rws"); try { oldFile.seek(0); int oldVersion = oldFile.readInt(); oldFile.close(); oldFile = null; if (oldVersion < LAST_PRE_UPGRADE_LAYOUT_VERSION) return false; } finally { IOUtils.cleanup(LOG, oldFile); } return true; }
From source file:com.evolveum.midpoint.model.impl.controller.ModelDiagController.java
private LogFileContentType getLogFileFragment(File logFile, Long fromPosition, Long maxSize) throws IOException { LogFileContentType rv = new LogFileContentType(); RandomAccessFile log = null; try {//from w w w . jav a 2 s . c o m log = new RandomAccessFile(logFile, "r"); long currentLength = log.length(); rv.setLogFileSize(currentLength); long start; if (fromPosition == null) { start = 0; } else if (fromPosition >= 0) { start = fromPosition; } else { start = Math.max(currentLength + fromPosition, 0); } rv.setAt(start); log.seek(start); long bytesToRead = Math.max(currentLength - start, 0); if (maxSize != null && maxSize < bytesToRead) { bytesToRead = maxSize; rv.setComplete(false); } else { rv.setComplete(true); } if (bytesToRead == 0) { return rv; } else if (bytesToRead > Integer.MAX_VALUE) { throw new IllegalStateException("Too many bytes to read from log file: " + bytesToRead); } byte[] buffer = new byte[(int) bytesToRead]; log.readFully(buffer); rv.setContent(new String(buffer)); return rv; } finally { if (log != null) { IOUtils.closeQuietly(log); } } }
From source file:FileBaseDataMap.java
/** * ?????.<br>/*from w w w .j a v a 2 s. co m*/ * ????null?.<br> * * @param * @return * @throws */ public List getAllOneFileInKeys() { List keys = null; byte[] datas = null; StringBuffer keysBuf = null; try { if (this.nowIterationFileIndex < this.dataFileList.length) { keys = new ArrayList(); datas = new byte[new Long(this.dataFileList[this.nowIterationFileIndex].length()).intValue()]; RandomAccessFile raf = new RandomAccessFile(this.dataFileList[this.nowIterationFileIndex], "rwd"); raf.seek(0); int readLen = -1; readLen = raf.read(datas); if (readLen > 0) { int loop = readLen / lineDataSize; for (int loopIdx = 0; loopIdx < loop; loopIdx++) { int assist = (lineDataSize * loopIdx); keysBuf = new StringBuffer(); int idx = 0; while (true) { if (datas[assist + idx] != 38) { keysBuf.append(new String(datas, assist + idx, 1)); } else { break; } idx++; } keys.add(keysBuf.toString()); } } } this.nowIterationFileIndex++; } catch (Exception e) { e.printStackTrace(); } return keys; }
From source file:org.mhisoft.wallet.service.AttachmentService.java
/** * Append to the existing store for Merged and Created/Updated attachments. * @param filename//from w w w. java2 s . c om * @param model * @param encryptor */ protected void appendAttachmentStore(final String filename, final WalletModel model, final PBEEncryptor encryptor) { FileAccessTable t = new FileAccessTable(); for (WalletItem item : model.getItemsFlatList()) { if (item.getAttachmentEntry() == null) continue; if (item.getAttachmentEntry().getAccessFlag() == FileAccessFlag.Merge) { t.addEntry(item.getAttachmentEntry()); } else if (FileAccessFlag.Create == item.getAttachmentEntry().getAccessFlag() || FileAccessFlag.Update == item.getAttachmentEntry().getAccessFlag()) { if (item.getNewAttachmentEntry() != null && item.getNewAttachmentEntry().getFile() != null) { t.addEntry(item.getNewAttachmentEntry()); } else if (item.getAttachmentEntry().getFile() != null) { t.addEntry(item.getAttachmentEntry()); } } } RandomAccessFile attachmentFileStore = null; try { attachmentFileStore = new RandomAccessFile(filename, "rw"); if (t.getSize() > 0) { //write the total number of entries first int entriesCount = attachmentFileStore.readInt(); //add to be appended ones entriesCount += t.getSize(); attachmentFileStore.seek(0); attachmentFileStore.writeInt(entriesCount); //seek to the end long itemStartPos = attachmentFileStore.length(); attachmentFileStore.seek(itemStartPos); //append new entries to the end of the store. writeFileEntries(model, false, filename, itemStartPos, attachmentFileStore, t, model.getEncryptorForRead(), encryptor); } /*marked the deleted entries **/ for (WalletItem item : model.getItemsFlatList()) { if (item.getAttachmentEntry() == null) continue; if (FileAccessFlag.Delete == item.getAttachmentEntry().getAccessFlag() //the attachment is deleted //the entry had the content saved in the store, now it is replaced. the new content is appended to the end of the file. // the file entry at the old position needs to be marked as DELETE. || (FileAccessFlag.Update == item.getAttachmentEntry().getAccessFlag() && item.getAttachmentEntry().getEncSize() > 0) && item.getAttachmentEntry().getPosition() > 0) { attachmentFileStore.seek(item.getAttachmentEntry().getPosition() + 40); attachmentFileStore.writeInt(FileAccessFlag.Delete.ordinal()); } } attachmentFileStore.close(); attachmentFileStore = null; } catch (IOException e) { e.printStackTrace(); DialogUtils.getInstance().error("Error writing attachment entries.", e.getMessage()); } finally { if (attachmentFileStore != null) try { attachmentFileStore.close(); } catch (IOException e) { //e.printStackTrace(); } } }