List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
From source file:edu.tsinghua.lumaqq.IPSeeker.java
/** * ?/*from w w w .jav a2 s. c om*/ */ private IPSeeker() { ipCache = new HashMap<String, IPLocation>(); loc = new IPLocation(); buf = new byte[100]; b4 = new byte[4]; b3 = new byte[3]; try { ipFile = new RandomAccessFile(LumaQQ.IP_FILE, "r"); } catch (FileNotFoundException e) { // ????????? // ???ip?? String filename = new File(LumaQQ.IP_FILE).getName().toLowerCase(); File[] files = new File(LumaQQ.INSTALL_DIR).listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { if (files[i].getName().toLowerCase().equals(filename)) { try { ipFile = new RandomAccessFile(files[i], "r"); } catch (FileNotFoundException e1) { log.error("IP??IP"); ipFile = null; } break; } } } } // ??? if (ipFile != null) { try { ipBegin = readLong4(0); ipEnd = readLong4(4); if (ipBegin == -1 || ipEnd == -1) { ipFile.close(); ipFile = null; } } catch (IOException e) { log.error("IP???IP"); ipFile = null; } } }
From source file:name.npetrovski.jphar.DataEntry.java
@Override public InputStream getInputStream() throws IOException { if (null != source && source.exists() && source.isFile()) { if (null != offset) { int size = entryManifest.getCompressedSize(); if (!isDirectory() && size > 0) { try (RandomAccessFile raf = new RandomAccessFile(source, "r")) { byte[] data = new byte[size]; raf.seek(offset);/*from ww w .j a v a2 s. c o m*/ raf.read(data, 0, size); raf.close(); return getCompressorInputStream(new ByteArrayInputStream(data), entryManifest.getCompression().getType()); } } } else { return new FileInputStream(source); } } return null; }
From source file:com.adaptris.core.fs.CompositeFileFilterTest.java
private void write(long size, File f) throws IOException { RandomAccessFile rf = new RandomAccessFile(f, "rw"); rf.setLength(size);/*from w ww . j a v a 2 s . co m*/ rf.close(); }
From source file:com.ettrema.zsync.UploadReader.java
/** * Copies blocks of data from the input File to the output File. For each RelocateRange A-B/C in relocRanges, * the block starting at A and ending at B-1 is copied from inFile and written to byte C of outFile. * //from w ww . ja va 2s .c o m * @param inFile The server's File being replaced * @param relocRanges The Enumeration of RelocateRanges parsed from the Upload's relocStream * @param blocksize The block size used in relocRanges * @param outFile The File being assembled * @throws IOException */ public static void moveBlocks(File inFile, Enumeration<RelocateRange> relocRanges, int blocksize, File outFile) throws IOException { /* * Because transferFrom can supposedly throw Exceptions when copying large Files, * this method invokes moveRange to copy incrementally */ /*The FileChannels should be obtained from a RandomAccessFile rather than a *Stream, or the position() method will not work correctly */ FileChannel rc = null; FileChannel wc = null; try { rc = new RandomAccessFile(inFile, "r").getChannel(); wc = new RandomAccessFile(outFile, "rw").getChannel(); while (relocRanges.hasMoreElements()) { moveRange(rc, relocRanges.nextElement(), blocksize, wc); } } finally { Util.close(rc); Util.close(wc); } }
From source file:com.twinsoft.convertigo.beans.steps.WriteXMLStep.java
protected void writeFile(String filePath, NodeList nodeList) throws EngineException { if (nodeList == null) { throw new EngineException("Unable to write to xml file: element is Null"); }/*from w w w .j a v a 2 s .c om*/ String fullPathName = getAbsoluteFilePath(filePath); synchronized (Engine.theApp.filePropertyManager.getMutex(fullPathName)) { try { String encoding = getEncoding(); encoding = encoding.length() > 0 && Charset.isSupported(encoding) ? encoding : "UTF-8"; if (!isReallyAppend(fullPathName)) { String tTag = defaultRootTagname.length() > 0 ? StringUtils.normalize(defaultRootTagname) : "document"; FileUtils.write(new File(fullPathName), "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n<" + tTag + "/>", encoding); } StringBuffer content = new StringBuffer(); /* do the content, only append child element */ for (int i = 0; i < nodeList.getLength(); i++) { if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) { content.append(XMLUtils.prettyPrintElement((Element) nodeList.item(i), true, true)); } } /* detect current xml encoding */ RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(fullPathName, "rw"); FileChannel fc = randomAccessFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(60); int nb = fc.read(buf); String sbuf = new String(buf.array(), 0, nb, "ASCII"); String enc = sbuf.replaceFirst("^.*encoding=\"", "").replaceFirst("\"[\\d\\D]*$", ""); if (!Charset.isSupported(enc)) { enc = encoding; } buf.clear(); /* retrieve last header tag*/ long pos = fc.size() - buf.capacity(); if (pos < 0) { pos = 0; } nb = fc.read(buf, pos); boolean isUTF8 = Charset.forName(enc) == Charset.forName("UTF-8"); if (isUTF8) { for (int i = 0; i < buf.capacity(); i++) { sbuf = new String(buf.array(), i, nb - i, enc); if (!sbuf.startsWith("")) { pos += i; break; } } } else { sbuf = new String(buf.array(), 0, nb, enc); } int lastTagIndex = sbuf.lastIndexOf("</"); if (lastTagIndex == -1) { int iend = sbuf.lastIndexOf("/>"); if (iend != -1) { lastTagIndex = sbuf.lastIndexOf("<", iend); String tagname = sbuf.substring(lastTagIndex + 1, iend); content = new StringBuffer( "<" + tagname + ">\n" + content.toString() + "</" + tagname + ">"); } else { throw new EngineException("Malformed XML file"); } } else { content.append(sbuf.substring(lastTagIndex)); if (isUTF8) { String before = sbuf.substring(0, lastTagIndex); lastTagIndex = before.getBytes(enc).length; } } fc.write(ByteBuffer.wrap(content.toString().getBytes(enc)), pos + lastTagIndex); } finally { if (randomAccessFile != null) { randomAccessFile.close(); } } } catch (IOException e) { throw new EngineException("Unable to write to xml file", e); } finally { Engine.theApp.filePropertyManager.releaseMutex(fullPathName); } } }
From source file:com.linkedin.pinot.core.index.writer.impl.FixedBitSkipListSCMVWriter.java
public FixedBitSkipListSCMVWriter(File file, int numDocs, int totalNumValues, int columnSizeInBits) throws Exception { float averageValuesPerDoc = totalNumValues / numDocs; this.docsPerChunk = (int) (Math.ceil(PREFERRED_NUM_VALUES_PER_CHUNK / averageValuesPerDoc)); this.numChunks = (numDocs + docsPerChunk - 1) / docsPerChunk; chunkOffsetHeaderSize = numChunks * SIZE_OF_INT * NUM_COLS_IN_HEADER; bitsetSize = (totalNumValues + 7) / 8; rawDataSize = ((long) totalNumValues * columnSizeInBits + 7) / 8; totalSize = chunkOffsetHeaderSize + bitsetSize + rawDataSize; raf = new RandomAccessFile(file, "rw"); chunkOffsetsBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0, chunkOffsetHeaderSize, file, this.getClass().getSimpleName() + " chunkOffsetsBuffer"); bitsetBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, chunkOffsetHeaderSize, bitsetSize, file, this.getClass().getSimpleName() + " bitsetBuffer"); rawDataBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, chunkOffsetHeaderSize + bitsetSize, rawDataSize, file, this.getClass().getSimpleName() + " rawDataBuffer"); chunkOffsetsWriter = new FixedByteWidthRowColDataFileWriter(chunkOffsetsBuffer, numDocs, NUM_COLS_IN_HEADER, new int[] { SIZE_OF_INT }); customBitSet = CustomBitSet.withByteBuffer(bitsetSize, bitsetBuffer); rawDataWriter = new FixedBitWidthRowColDataFileWriter(rawDataBuffer, totalNumValues, 1, new int[] { columnSizeInBits }); }
From source file:dk.statsbiblioteket.util.LineReaderTest.java
public void testNIO() throws Exception { byte[] INITIAL = new byte[] { 1, 2, 3, 4 }; byte[] EXTRA = new byte[] { 5, 6, 7, 8 }; byte[] FULL = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; byte[] FIFTH = new byte[] { 87 }; byte[] FULL_WITH_FIFTH = new byte[] { 1, 2, 3, 4, 87, 6, 7, 8 }; // Create temp-file with content File temp = createTempFile(); FileOutputStream fileOut = new FileOutputStream(temp, true); fileOut.write(INITIAL);/* w w w. j a va2 s .c o m*/ fileOut.close(); checkContent("The plain test-file should be correct", temp, INITIAL); { // Read the 4 bytes RandomAccessFile input = new RandomAccessFile(temp, "r"); FileChannel channelIn = input.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(4096); channelIn.position(0); assertEquals("Buffer read should read full length", INITIAL.length, channelIn.read(buffer)); buffer.position(0); checkContent("Using buffer should produce the right bytes", INITIAL, buffer); channelIn.close(); input.close(); } { // Fill new buffer ByteBuffer outBuffer = ByteBuffer.allocate(4096); outBuffer.put(EXTRA); outBuffer.flip(); assertEquals("The limit of the outBuffer should be correct", EXTRA.length, outBuffer.limit()); // Append new buffer to end RandomAccessFile output = new RandomAccessFile(temp, "rw"); FileChannel channelOut = output.getChannel(); channelOut.position(INITIAL.length); assertEquals("All bytes should be written", EXTRA.length, channelOut.write(outBuffer)); channelOut.close(); output.close(); checkContent("The resulting file should have the full output", temp, FULL); } { // Fill single byte buffer ByteBuffer outBuffer2 = ByteBuffer.allocate(4096); outBuffer2.put(FIFTH); outBuffer2.flip(); assertEquals("The limit of the second outBuffer should be correct", FIFTH.length, outBuffer2.limit()); // Insert byte in the middle RandomAccessFile output2 = new RandomAccessFile(temp, "rw"); FileChannel channelOut2 = output2.getChannel(); channelOut2.position(4); assertEquals("The FIFTH should be written", FIFTH.length, channelOut2.write(outBuffer2)); channelOut2.close(); output2.close(); checkContent("The resulting file with fifth should be complete", temp, FULL_WITH_FIFTH); } }
From source file:com.android.volley.toolbox.UploadNetwork.java
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = Collections.emptyMap(); RandomAccessFile acessfile = null; File file = null;/* w ww. ja v a2s . c o m*/ try { if (!(request instanceof DownOrUpRequest)) { throw new IllegalArgumentException("request object mast be DownOrUpRequest???"); } DownOrUpRequest requestDown = (DownOrUpRequest) request; // Gather headers. Map<String, String> headers = new HashMap<String, String>(); // Download have no cache String url = requestDown.getUrl(); String name = url.substring(url.lastIndexOf('/'), url.length()); String path = requestDown.getDownloadPath(); String filePath = ""; if (path.endsWith("/")) { filePath = path + name; } else { path = path + "/"; filePath = path + "/" + name; } File dir = new File(path); dir.mkdirs(); file = File.createTempFile(path, null, dir); acessfile = new RandomAccessFile(file, "rws"); long length = acessfile.length(); acessfile.seek(length); // Range: bytes=5275648- headers.put("Range", "bytes=" + length + "-");// httpResponse = mHttpStack.performRequest(requestDown, headers); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, requestDown, responseContents, statusLine); if (statusCode < 200 || statusCode > 299) { acessfile.close(); throw new IOException(); } // Some responses such as 204s do not have content. We must check. if (httpResponse.getEntity() != null) { responseContents = entityToBytes(httpResponse.getEntity(), requestDown, acessfile); } else { // Add 0 byte response as a way of honestly representing a // no-content request. responseContents = new byte[0]; } acessfile.close(); file.renameTo(new File(filePath)); return new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { if (acessfile != null) { try { acessfile.close(); file.delete(); } catch (IOException e1) { e1.printStackTrace(); } } int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusLine().getStatusCode(); } else { throw new NoConnectionError(e); } VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); throw new NetworkError(networkResponse); } } }
From source file:com.linkedin.pinot.core.io.writer.impl.v1.FixedBitMultiValueWriter.java
public FixedBitMultiValueWriter(File file, int numDocs, int totalNumValues, int columnSizeInBits) throws Exception { float averageValuesPerDoc = totalNumValues / numDocs; this.docsPerChunk = (int) (Math.ceil(PREFERRED_NUM_VALUES_PER_CHUNK / averageValuesPerDoc)); this.numChunks = (numDocs + docsPerChunk - 1) / docsPerChunk; chunkOffsetHeaderSize = numChunks * SIZE_OF_INT * NUM_COLS_IN_HEADER; bitsetSize = (totalNumValues + 7) / 8; rawDataSize = ((long) totalNumValues * columnSizeInBits + 7) / 8; totalSize = chunkOffsetHeaderSize + bitsetSize + rawDataSize; raf = new RandomAccessFile(file, "rw"); chunkOffsetsBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0, chunkOffsetHeaderSize, file, this.getClass().getSimpleName() + " chunkOffsetsBuffer"); bitsetBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, chunkOffsetHeaderSize, bitsetSize, file, this.getClass().getSimpleName() + " bitsetBuffer"); rawDataBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, chunkOffsetHeaderSize + bitsetSize, rawDataSize, file, this.getClass().getSimpleName() + " rawDataBuffer"); chunkOffsetsWriter = new FixedByteSingleValueMultiColWriter(chunkOffsetsBuffer, numDocs, NUM_COLS_IN_HEADER, new int[] { SIZE_OF_INT }); customBitSet = CustomBitSet.withByteBuffer(bitsetSize, bitsetBuffer); rawDataWriter = new FixedBitSingleValueMultiColWriter(rawDataBuffer, totalNumValues, 1, new int[] { columnSizeInBits }); }
From source file:jazsync.UploadTests.java
/** * Sets the fields of an Upload object and tests whether the {@link Upload#getInputStream()} * returns the upload data in the expected format. * // w w w.j av a2 s . co m * @throws IOException */ @Test public void testGetInputStream() throws IOException { Upload um = new Upload(); um.setVersion("testVersion"); um.setBlocksize(1024); um.setFilelength(32768); um.setSha1("sha1checksum"); File testFile = File.createTempFile("Upload", "Test"); RandomAccessFile randAccess = new RandomAccessFile(testFile, "rw"); String inString = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXABCDEYZXXXXX"; randAccess.write(inString.getBytes("US-ASCII")); ByteRangeWriter dataRanges = new ByteRangeWriter(16384); dataRanges.add(new Range(45, 50), randAccess); dataRanges.add(new Range(51, 52), randAccess); um.setDataStream(dataRanges.getInputStream()); RelocWriter relocRanges = new RelocWriter(16384); relocRanges.add(new RelocateRange(new Range(2, 6), 123)); relocRanges.add(new RelocateRange(new Range(8, 98), 987)); um.setRelocStream(relocRanges.getInputStream()); InputStream uploadIn = um.getInputStream(); String actString = IOUtils.toString(uploadIn, Upload.CHARSET); String expString = version + filelength + blocksize + sha1 + relocString + rangeString; uploadIn.close(); randAccess.close(); System.out.println(actString); Assert.assertEquals(expString, actString); }