/** * Reads a file from the given InputStream and saves it into the local download directory * * @param in The InputStream from which to read the file * @param start The starting byte of the piece that will be downloaded from this peer * @param end The end byte (exclusive) of the piece that will be downloaded from this peer * @throws java.io.IOException if an error occurs while downloading the file */ private void saveFile(InputStream in, int start, int end) throws IOException { if (start >= end) { throw new IllegalStateException( "Start byte (" + start + ") must be less than the end byte (" + end + ")"); } RandomAccessFile fileOut = null; try { File downloadFile = new File(Client.downloadDir, _file); // Open the file in read/write mode with synchronous content/metadata writing fileOut = new RandomAccessFile(downloadFile, "rws"); fileOut.seek(start); byte[] bytes = new byte[_chunkSize]; int bytesRead; int pos = start; while ((bytesRead = in.read(bytes, 0, _chunkSize)) >= 0 && pos < end) { fileOut.write(bytes, 0, Math.min(bytesRead, end - pos)); pos += bytesRead; } } catch (SocketException e) { System.err.println( "[DownloadFromPeerRunnable] Disconnected from peer at " + _peer.getInetAddress()); _callback.onFinishChunk(_file, false); } finally { if (fileOut != null) { try { fileOut.close(); } catch (IOException e) { e.printStackTrace(); } } } }
private void execFormatTrackTask() { File file = this.ioFile; long pos = this.ioFilePos; int cnt = this.ioByteCnt; if ((file != null) && (pos >= 0) && (cnt > 0)) { boolean err = false; RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "rw"); raf.seek(pos); while (cnt > 0) { raf.write(0); --cnt; } raf.close(); raf = null; } catch (IOException ex) { err = true; if (!this.writeErrShown) { this.writeErrShown = true; EmuUtil.fireShowError(this.owner, null, ex); } } finally { EmuUtil.doClose(raf); } if (err) { this.errorReg = ERROR_UNCORRECTABLE_DATA; this.statusReg |= STATUS_ERROR; } fireInterrupt(); } }
public void saveMetaData() throws IOException { pageFile.seek(offset); pageFile.writeInt(nextPageId); pageFile.writeInt(currentFill); pageFile.writeInt(bloomfilter); pageFile.writeByte(type); }
public String[] getNextRecord() { try { String ans[] = new String[3]; String line; while ((line = filein.readLine()) != null) { // get description if (!line.substring(0, 1).equals("@")) return null; ans[0] = line.substring(1); String seq = ""; String qual = ""; while ((line = filein.readLine()) != null) { if (line.matches("[ACTGNacgtnURYSWKMBDHVN.-]*")) { seq += line; } else { if (!line.substring(0, 1).equals("+")) return null; // ans[2] = line.substring(1); while ((line = filein.readLine()) != null) { qual += line; if (seq.length() <= qual.length()) { ans[1] = seq; ans[2] = qual; return ans; } } } } } return null; } catch (Exception e) { return null; } }
public void run() { try { System.out.println("socked"); sock = new Socket(ii, pp); oout = new ObjectOutputStream(sock.getOutputStream()); oout.flush(); oin = new ObjectInputStream(sock.getInputStream()); System.out.println("read "); rf.setLength(0); do { System.out.println("read "); file f = (file) oin.readObject(); if (f.length <= 0) break; write(f); } while (true); oout.close(); oin.close(); rf.close(); sock.close(); xx.ConfirmPopup("Haua file namano shesh!!!"); } catch (Exception e) { e.printStackTrace(); } }
/** * Add the given text string to the end of a given file. * * @param inStr The string to be added. * @param fileStr the name of the file to be added. */ public static void addStringToFile(String inStr, String fileStr) throws Exception { RandomAccessFile raFile = new RandomAccessFile(fileStr, "rw"); raFile.seek(raFile.length()); raFile.writeBytes(inStr); raFile.close(); }
/** * Loads a query from the mgf file. * * @param file The file to read the query from. * @param indexElement The index element pointing to that specific ms2 query. * @return * @oaram index The query's 1-based index in the MGF file. This index is stored in the returned * Ms2Query object. */ private static Ms2Query loadIndexedQueryFromFile(File file, IndexElement indexElement, int index) throws JMzReaderException { RandomAccessFile accFile = null; try { accFile = new RandomAccessFile(file, "r"); // read the indexed element byte[] byteBuffer = new byte[indexElement.getSize()]; // read the file from there accFile.seek(indexElement.getStart()); accFile.read(byteBuffer); String ms2Buffer = new String(byteBuffer); // create the query Ms2Query query = new Ms2Query(ms2Buffer, index); return query; } catch (FileNotFoundException e) { throw new JMzReaderException("MGF file could not be found.", e); } catch (IOException e) { throw new JMzReaderException("Failed to read from MGF file", e); } finally { if (accFile != null) { try { accFile.close(); } catch (IOException e) { // ignore } } } }
public static boolean clearWorldReference(World world) { String worldname = world.getName(); if (regionfiles == null) return false; if (rafField == null) return false; ArrayList<Object> removedKeys = new ArrayList<Object>(); try { for (Object o : regionfiles.entrySet()) { Map.Entry e = (Map.Entry) o; File f = (File) e.getKey(); if (f.toString().startsWith("." + File.separator + worldname)) { SoftReference ref = (SoftReference) e.getValue(); try { RegionFile file = (RegionFile) ref.get(); if (file != null) { RandomAccessFile raf = (RandomAccessFile) rafField.get(file); raf.close(); removedKeys.add(f); } } catch (Exception ex) { ex.printStackTrace(); } } } } catch (Exception ex) { MyWorlds.log( Level.WARNING, "Exception while removing world reference for '" + worldname + "'!"); ex.printStackTrace(); } for (Object key : removedKeys) { regionfiles.remove(key); } return true; }
/** * Copy the given byte range of the given input to the given output. * * @param input The input to copy the given range to the given output for. * @param output The output to copy the given range from the given input for. * @param start Start of the byte range. * @param length Length of the byte range. * @throws IOException If something fails at I/O level. */ private static void copy(RandomAccessFile input, OutputStream output, long start, long length) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int read; if (input.length() == length) { // Write full range. while ((read = input.read(buffer)) > 0) { output.write(buffer, 0, read); } } else { // Write partial range. input.seek(start); long toRead = length; while ((read = input.read(buffer)) > 0) { if ((toRead -= read) > 0) { output.write(buffer, 0, read); } else { output.write(buffer, 0, (int) toRead + read); break; } } } }
private ChannelFuture sendFile(ChannelHandlerContext ctx, Channel ch, FileChunk file) throws IOException { RandomAccessFile raf; try { raf = new RandomAccessFile(file.getFile(), "r"); } catch (FileNotFoundException fnfe) { return null; } ChannelFuture writeFuture; if (ch.getPipeline().get(SslHandler.class) != null) { // Cannot use zero-copy with HTTPS. writeFuture = ch.write(new ChunkedFile(raf, file.startOffset(), file.length(), 8192)); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), file.startOffset(), file.length()); writeFuture = ch.write(region); writeFuture.addListener( new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { region.releaseExternalResources(); } }); } return writeFuture; }
public void pdfRead() { try { String INPUTFILE = "example_2.pdf"; File file = new File(INPUTFILE); RandomAccessFile raf = new RandomAccessFile(file, "r"); FileChannel channel = raf.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); PDFFile pdffile = new PDFFile(buf); // draw the first page to an image PDFPage page = pdffile.getPage(0); // get the width and height for the doc at the default zoom Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight()); // generate the image Image img = page.getImage( rect.width, rect.height, // width & height rect, // clip rect null, // null for the ImageObserver true, // fill background with white true // block until drawing is done ); frame.getContentPane().add(new JLabel(new ImageIcon(img))); frame.pack(); frame.setSize(600, 700); } catch (Exception e) { System.out.println(e); } }
/** Met dans le cache le résultat de l'url indiquée */ public boolean putInCache(String url) throws Exception { // Lecture MyInputStream in = null; try { in = Util.openStream(url); byte buf[] = in.readFully(); // Nettoyage et Ecriture String id = codage(url); File g = new File(dir + Util.FS + id); g.delete(); RandomAccessFile f = null; try { f = new RandomAccessFile(dir + Util.FS + id, "rw"); f.write(buf); } finally { if (f != null) f.close(); } aladin.trace(3, "Put in cache [" + url + "]"); return true; } catch (Exception e) { if (aladin.levelTrace >= 3) e.printStackTrace(); } finally { if (in != null) in.close(); } return false; }
/** * Read a file offset from the file PST Files have this tendency to store file offsets (pointers) * in 8 little endian bytes. Convert this to a long for seeking to. * * @param in handle for PST file * @param startOffset where to read the 8 bytes from * @return long representing the read location * @throws IOException */ protected long extractLEFileOffset(long startOffset) throws IOException { long offset = 0; if (this.getPSTFileType() == PSTFile.PST_TYPE_ANSI) { in.seek(startOffset); byte[] temp = new byte[4]; in.read(temp); offset |= temp[3] & 0xff; offset <<= 8; offset |= temp[2] & 0xff; offset <<= 8; offset |= temp[1] & 0xff; offset <<= 8; offset |= temp[0] & 0xff; } else { in.seek(startOffset); byte[] temp = new byte[8]; in.read(temp); offset = temp[7] & 0xff; long tmpLongValue; for (int x = 6; x >= 0; x--) { offset = offset << 8; tmpLongValue = (long) temp[x] & 0xff; offset |= tmpLongValue; } } return offset; }
/* write a chunk data to the region file at specified sector number */ private void write(int sectorNumber, byte[] data, int length) throws IOException { debugln(" " + sectorNumber); file.seek(sectorNumber * SECTOR_BYTES); file.writeInt(length + 1); // chunk length file.writeByte(VERSION_DEFLATE); // chunk version number file.write(data, 0, length); // chunk data }
public static DigestBlob resumeTransfer( BlobContainer blobContainer, String digest, UUID transferId, long currentPos) { DigestBlob digestBlob = new DigestBlob(blobContainer, digest, transferId); digestBlob.file = getTmpFilePath(blobContainer, digest, transferId); try { logger.trace("Resuming DigestBlob {}. CurrentPos {}", digest, currentPos); digestBlob.headFileChannel = new FileOutputStream(digestBlob.file, false).getChannel(); digestBlob.headLength = currentPos; digestBlob.headSize = new AtomicLong(); digestBlob.headCatchedUpLatch = new CountDownLatch(1); RandomAccessFile raf = new RandomAccessFile(digestBlob.file, "rw"); raf.setLength(currentPos); raf.close(); FileOutputStream outputStream = new FileOutputStream(digestBlob.file, true); digestBlob.fileChannel = outputStream.getChannel(); } catch (IOException ex) { logger.error("error resuming transfer of {}, id: {}", ex, digest, transferId); return null; } return digestBlob; }
// see DbFile.java for javadocs public ArrayList<Page> insertTuple(TransactionId tid, Tuple t) throws DbException, IOException, TransactionAbortedException { // some code goes here BufferPool bp = Database.getBufferPool(); int id = getId(), i, slots; ArrayList<Page> retlist = new ArrayList<Page>(); PageId pid = null; HeapPage p = null; for (i = 0; i < numPages(); i++) { pid = new HeapPageId(id, i); p = (HeapPage) bp.getPage(tid, pid, Permissions.READ_WRITE); slots = p.getNumEmptySlots(); if (slots > 0) { p.insertTuple(t); retlist.add(p); return retlist; } } // create new page and add tuple to it pid = new HeapPageId(id, i); raf.setLength(raf.length() + BufferPool.PAGE_SIZE); p = (HeapPage) bp.getPage(tid, pid, Permissions.READ_WRITE); p.insertTuple(t); retlist.add(p); return retlist; }
/** * Reads an array of strings from the TIFF file. * * @param count Number of strings to read * @param value Offset from which to read */ protected String[] readASCIIArray(long count, long value) throws IOException { _raf.seek(value); int nstrs = 0; List list = new LinkedList(); byte[] buf = new byte[(int) count]; _raf.read(buf); StringBuffer strbuf = new StringBuffer(); for (int i = 0; i < count; i++) { int b = buf[i]; if (b == 0) { list.add(strbuf.toString()); strbuf.setLength(0); } else { strbuf.append((char) b); } } /* We can't use ArrayList.toArray because that returns an Object[], not a String[] ... sigh. */ String[] strs = new String[nstrs]; ListIterator iter = list.listIterator(); for (int i = 0; i < nstrs; i++) { strs[i] = (String) iter.next(); } return strs; }
/** * Ecrit la piece donnée dans le fichier temporaire sur le disque * * @param piece : pièce à écrire * @param num : numéros de la pièce */ private synchronized void writePieceTmpFile(byte[] piece, int num) { if (num < 0 || num >= this.nbPieces()) { throw new IllegalArgumentException(); } if (piece.length > _piecesize) { throw new IllegalArgumentException(); } try { RandomAccessFile writer_tmp = new RandomAccessFile(this, "rw"); FileChannel writer = writer_tmp.getChannel(); int index_piece = ((int) this.length() - this.headerSize()) / _piecesize; if (piece.length < _piecesize) { piece = Arrays.copyOf(piece, _piecesize); } Tools.write(writer, 4 + _key.length() + 4 + 4 + 4 * num, index_piece); Tools.write(writer, this.headerSize() + _piecesize * index_piece, piece); writer.force(true); writer_tmp.close(); } catch (Exception e) { System.out.println("Unable to write tmp file piece"); e.printStackTrace(); } }
/** * Fills the buffer with more data, taking into account shuffling and other tricks for dealing * with marks. Assumes that it is being called by a synchronized method. This method also assumes * that all data has already been read in, hence pos > count. */ private void fill() throws IOException { if (markpos < 0) { pos = 0; /* no mark: throw away the buffer */ bufpos += count; } else if (pos >= buf.length) /* no room left in buffer */ if (markpos > 0) { /* can throw away early part of the buffer */ int sz = pos - markpos; System.arraycopy(buf, markpos, buf, 0, sz); pos = sz; bufpos += markpos; markpos = 0; } else if (buf.length >= marklimit) { markpos = -1; /* buffer got too big, invalidate mark */ pos = 0; /* drop buffer contents */ bufpos += count; } else { /* grow buffer */ int nsz = pos * 2; if (nsz > marklimit) nsz = marklimit; byte nbuf[] = new byte[nsz]; System.arraycopy(buf, 0, nbuf, 0, pos); buf = nbuf; } count = pos; // limit to datalen int len = buf.length - pos; if (bufpos - start + pos + len > datalen) len = (int) (datalen - (bufpos - start + pos)); synchronized (in) { in.seek(bufpos + pos); int n = in.read(buf, pos, len); if (n > 0) count = n + pos; } }
public void write(Tag tag, RandomAccessFile raf, RandomAccessFile tempRaf) throws CannotWriteException, IOException { FileChannel fc = raf.getChannel(); int oldTagSize = 0; if (tagExists(fc)) { // read the length if (!canOverwrite(raf)) throw new CannotWriteException("Overwritting of this kind of ID3v2 tag not supported yet"); fc.position(6); ByteBuffer buf = ByteBuffer.allocate(4); fc.read(buf); oldTagSize = (buf.get(0) & 0xFF) << 21; oldTagSize += (buf.get(1) & 0xFF) << 14; oldTagSize += (buf.get(2) & 0xFF) << 7; oldTagSize += buf.get(3) & 0xFF; oldTagSize += 10; // System.err.println("Old tag size: "+oldTagSize); int newTagSize = tc.getTagLength(tag); if (oldTagSize >= newTagSize) { // replace // System.err.println("Old ID32v Tag found, replacing the old // tag"); fc.position(0); fc.write(tc.convert(tag, oldTagSize - newTagSize)); // ID3v2 Tag Written return; } } // create new tag with padding // System.err.println("Creating a new ID3v2 Tag"); fc.position(oldTagSize); if (fc.size() > 15 * 1024 * 1024) { FileChannel tempFC = tempRaf.getChannel(); tempFC.position(0); tempFC.write(tc.convert(tag, Id3v2TagCreator.DEFAULT_PADDING)); tempFC.transferFrom(fc, tempFC.position(), fc.size() - oldTagSize); fc.close(); } else { ByteBuffer[] content = new ByteBuffer[2]; content[1] = ByteBuffer.allocate((int) fc.size()); fc.read(content[1]); content[1].rewind(); content[0] = tc.convert(tag, Id3v2TagCreator.DEFAULT_PADDING); fc.position(0); fc.write(content); } }
public int bubbleSort() throws Exception { boolean swapped = true; int j = 0; int counter = 0; while (swapped) { swapped = false; j++; for (int i = 0; i < length() - j; i++) { file.seek(i * 4); int one = file.readInt(); int two = file.readInt(); if (one > two) { file.seek(i * 4); file.writeInt(two); file.writeInt(one); swapped = true; counter++; } } } return counter; }
/** * Create an index file for the specified column. * * @param colname the column's name * @return the time it took to run this method. * @throws Exception */ public long createIndexFile() throws Exception { long s = System.currentTimeMillis(); // fill idx file with hashsize empty records/lines (empty means filled with spaces) int pkindex = def.getColPosition(def.getPK()); if (pkindex == -1) { throw new Exception("Primary key does not exist"); } Integer[] size = def.getSizes(); int recordSize = idxFixedRecordLength() + size[pkindex]; StringBuffer temp = new StringBuffer(); for (int i = 0; i < recordSize - 2; i++) { temp.append(" "); } indexFile.seek(0); for (int i = 0; i < this.hashsize; i++) { indexFile.writeBytes(temp + "\r\n"); } int table_pos = 0; // create an index entry for each row present in the tbl-file (for column=colname) String line = null; tableFile.seek(0); while ((line = tableFile.readLine()) != null) { // get column value (don't strip the spaces) String pkvalue = line.split("#")[pkindex]; addIndexEntry(table_pos, pkvalue); table_pos++; } long e = System.currentTimeMillis(); return e - s; }
public double getProgress() { try { return 1.0 * filein.getFilePointer() / (1.0 * filein.length()); } catch (IOException e) { return 1.0; } }
/** * Delete an index entry in the idx file of the specified column. * * @param colname the column's name * @param idxPos index entry (line nr) to be deleted * @throws Exception */ protected long deleteIndexEntry(String colname, int idxPos) throws Exception { long s = System.currentTimeMillis(); if (!indexExists(colname)) { throw new Exception("No index created"); } int pkindex = def.getColPosition(colname); if (pkindex == -1) { throw new Exception("Column does not exist"); } Integer[] size = def.getSizes(); int recordSize = idxFixedRecordLength() + size[pkindex]; indexFile.seek(idxPos * recordSize); String sLine = indexFile.readLine(); String[] parts = sLine.split("#"); if (Integer.parseInt(parts[0].trim()) != idxPos) { throw new Exception("Index not found in index file"); } else { indexFile.seek(idxPos * recordSize + 6); String flag = "D"; indexFile.write(flag.toString().getBytes()); } long e = System.currentTimeMillis(); return e - s; }
// call this method to write the description to the file // the file pointer must be already positioned // the description must have been set private void writeDescription() throws IOException { if (description.length() > DESCRIPTION_LENGTH) description = description.substring(0, DESCRIPTION_LENGTH); outStream.writeChars(description); for (int j = 0; j < (DESCRIPTION_LENGTH - description.length()); j++) outStream.writeChar(' '); }
public static void main(String[] args) { /*System.out.println(modular_exponent_32(2,36,37)); System.out.println(modular_exponent_32(2,18,37)); System.out.println(modular_exponent_32(2,9,37)); int d = Integer.numberOfTrailingZeros(64); System.out.println(d); */ int counter = how_many_primes(1000000); System.out.println(counter); try { RandomAccessFile out = new RandomAccessFile("mrprimes.txt", "rw"); out.writeBytes("2\n"); for (int i = 3; i < 1000000; i += 2) { if (miller_rabin_32(i)) { out.writeBytes(Integer.toString(i) + "\n"); } } // for (int i=0; i<counter; i++){ // out.seek(i*4); // System.out.println(","+out.readInt()); // } out.close(); } catch (IOException e) { } System.out.println(miller_rabin_32(1105)); }
public int luaCB_read(Lua l, LuaPlugin plugin) { l.pushNil(); l.pushNil(); try { long offset = (long) l.checkNumber(2); int length = (int) l.checkNumber(3); if (length <= 0) { l.pushNil(); l.pushString("Length is not positive"); return 2; } byte[] tmp = new byte[length]; object.seek(offset); length = object.read(tmp); if (length < 0) { l.pushNil(); l.pushNil(); return 2; } StringBuffer buf = new StringBuffer(length); for (byte x : tmp) buf.appendCodePoint((int) x & 0xFF); l.push(buf.toString()); } catch (IOException e) { l.pushNil(); l.pushString("IOException: " + e.getMessage()); return 2; } return 1; }
@Override public ByteBuffer readPage(File file, long position, ByteBuffer pageBuffer) throws IOException, InterruptedException { long start = System.currentTimeMillis(); RandomAccessFile randomAccessFile = randomAccessFile(file); try { randomAccessFile.seek(position); randomAccessFile.readFully(pageBuffer.array(), pageBuffer.arrayOffset(), pageSizeBytes); if (Thread.interrupted()) { throw new InterruptedException(); } long stop = System.currentTimeMillis(); if (LOG.isLoggable(Level.FINE)) { LOG.log( Level.FINE, "Read page at {0} of {1}: {2} msec", new Object[] {position, file, stop - start}); } } catch (EOFException e) { LOG.log( Level.SEVERE, "Caught EOFException while reading {0}, position {1}", new Object[] {file, position}); LOG.log(Level.SEVERE, "stack", e); throw e; } finally { randomAccessFile.close(); } return pageBuffer; }
public void loadMetaData() throws IOException { pageFile.seek(offset); nextPageId = pageFile.readInt(); currentFill = pageFile.readInt(); bloomfilter = pageFile.readInt(); type = pageFile.readByte(); }
/** @param workTokDir Token directory (common for multiple nodes). */ private void cleanupResources(File workTokDir) { RandomAccessFile lockFile = null; FileLock lock = null; try { lockFile = new RandomAccessFile(new File(workTokDir, LOCK_FILE_NAME), "rw"); lock = lockFile.getChannel().lock(); if (lock != null) processTokenDirectory(workTokDir); else if (log.isDebugEnabled()) log.debug( "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath()); } catch (OverlappingFileLockException ignored) { if (log.isDebugEnabled()) log.debug( "Token directory is being processed concurrently: " + workTokDir.getAbsolutePath()); } catch (FileLockInterruptionException ignored) { Thread.currentThread().interrupt(); } catch (IOException e) { U.error(log, "Failed to process directory: " + workTokDir.getAbsolutePath(), e); } finally { U.releaseQuiet(lock); U.closeQuiet(lockFile); } }