List of usage examples for java.io RandomAccessFile length
public native long length() throws IOException;
From source file:org.nuxeo.ecm.core.blob.binary.LocalBinaryManager.java
/** * Sets the last modification date to now on a file * * @param file the file// w ww.j a va 2 s. c om */ public static void touch(File file) { long time = System.currentTimeMillis(); if (file.setLastModified(time)) { // ok return; } if (!file.canWrite()) { // cannot write -> stop won't be able to delete anyway return; } try { // Windows: the file may be open for reading // workaround found by Thomas Mueller, see JCR-2872 RandomAccessFile r = new RandomAccessFile(file, "rw"); try { r.setLength(r.length()); } finally { r.close(); } } catch (IOException e) { log.error("Cannot set last modified for file: " + file, e); } }
From source file:org.apache.hadoop.dfs.TestDatanodeBlockScanner.java
private static void truncateReplica(String blockName, int dnIndex) throws IOException { File baseDir = new File(System.getProperty("test.build.data"), "dfs/data"); for (int i = dnIndex * 2; i < dnIndex * 2 + 2; i++) { File blockFile = new File(baseDir, "data" + (i + 1) + "/current/" + blockName); if (blockFile.exists()) { RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw"); raFile.setLength(raFile.length() - 1); raFile.close();/*from w w w . j a v a2 s . c o m*/ break; } } }
From source file:org.apache.hadoop.hdfs.TestDatanodeBlockScanner.java
/** * Change the length of a block at datanode dnIndex *///from w w w .ja v a 2 s . c o m static boolean changeReplicaLength(String blockName, int dnIndex, int lenDelta) throws IOException { File baseDir = new File(System.getProperty("test.build.data"), "dfs/data"); for (int i = dnIndex * 2; i < dnIndex * 2 + 2; i++) { File blockFile = new File(baseDir, "data" + (i + 1) + "/current/" + blockName); if (blockFile.exists()) { RandomAccessFile raFile = new RandomAccessFile(blockFile, "rw"); raFile.setLength(raFile.length() + lenDelta); raFile.close(); return true; } } return false; }
From source file:net.sourceforge.doddle_owl.data.JpnWordNetDic.java
private static long getIndexFileSize(RandomAccessFile indexFile) { try {// w w w .j av a2 s. c om return indexFile.length() / 10; } catch (IOException ioe) { ioe.printStackTrace(); } return -1; }
From source file:be.roots.taconic.pricingguide.util.iTextUtil.java
public static byte[] embedFont(byte[] pdf, String fontFileName, String fontName) throws IOException, DocumentException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { // the font file RandomAccessFile raf = new RandomAccessFile(fontFileName, "r"); byte fontfile[] = new byte[(int) raf.length()]; raf.readFully(fontfile);/*from w w w.j a v a 2 s . com*/ raf.close(); // create a new stream for the font file PdfStream stream = new PdfStream(fontfile); stream.flateCompress(); stream.put(PdfName.LENGTH1, new PdfNumber(fontfile.length)); // create a reader object PdfReader reader = new PdfReader(pdf); int n = reader.getXrefSize(); PdfObject object; PdfDictionary font; PdfStamper stamper = new PdfStamper(reader, baos); PdfName fontname = new PdfName(fontName); for (int i = 0; i < n; i++) { object = reader.getPdfObject(i); if (object == null || !object.isDictionary()) continue; font = (PdfDictionary) object; if (PdfName.FONTDESCRIPTOR.equals(font.get(PdfName.TYPE1)) && fontname.equals(font.get(PdfName.FONTNAME))) { PdfIndirectObject objref = stamper.getWriter().addToBody(stream); font.put(PdfName.FONTFILE2, objref.getIndirectReference()); } } stamper.close(); reader.close(); return baos.toByteArray(); } }
From source file:org.srlutils.Files.java
/** * wrapper for RandomAccessFile.read()//from w w w . ja v a 2 s. co m * read len bytes from filename at position, filling bites starting at offset * if multiple exceptions are encountered (eg due to close() failing) throws the first only * @param bites if null, allocate a new array and read all available bytes * @param len if negative, fill bites * @return the byte array and number of bytes read * @throws RuntimeException wrapping any exceptions */ public static ReadInfo readbytes(String filename, long position, byte[] bites, int offset, int len) { ReadInfo read = new ReadInfo(); RandomAccessFile fid = null; RuntimeException rte = null; try { String mode = "r"; // fixme:memleak -- looks like fid is leaked ... fid = new RandomAccessFile(filename, mode); if (bites == null) { long size = fid.length() - position; if (size + offset > Integer.MAX_VALUE) throw new Exception(String.format( "attempt to read the entirity of file '%s', size %d, is too large", filename, len)); len = (int) size; bites = new byte[len + offset]; } if (len < 0) len = bites.length - offset; fid.seek(position); read.num = fid.read(bites, offset, len); read.bytes = bites; return read; } catch (Exception ex) { rte = rte(ex, "failed to read string from file: %s", filename); throw rte; } finally { if (rte == null) rteClose(fid); else tryClose(fid); } }
From source file:net.sourceforge.doddle_owl.data.JpnWordNetDic.java
private static long getIndexFpListSize() { RandomAccessFile indexFpListFile = null; indexFpListFile = jpnwnWordIndexFile; try {//from w w w . j a v a2 s . co m return indexFpListFile.length() / 10; } catch (IOException ioe) { ioe.printStackTrace(); } return -1; }
From source file:com.googlecode.psiprobe.Utils.java
public static void sendFile(HttpServletRequest request, HttpServletResponse response, File file) throws IOException { OutputStream out = response.getOutputStream(); RandomAccessFile raf = new RandomAccessFile(file, "r"); try {/*w w w . j a va2 s . c om*/ long fileSize = raf.length(); long rangeStart = 0; long rangeFinish = fileSize - 1; // accept attempts to resume download (if any) String range = request.getHeader("Range"); if (range != null && range.startsWith("bytes=")) { String pureRange = range.replaceAll("bytes=", ""); int rangeSep = pureRange.indexOf("-"); try { rangeStart = Long.parseLong(pureRange.substring(0, rangeSep)); if (rangeStart > fileSize || rangeStart < 0) { rangeStart = 0; } } catch (NumberFormatException e) { // ignore the exception, keep rangeStart unchanged } if (rangeSep < pureRange.length() - 1) { try { rangeFinish = Long.parseLong(pureRange.substring(rangeSep + 1)); if (rangeFinish < 0 || rangeFinish >= fileSize) { rangeFinish = fileSize - 1; } } catch (NumberFormatException e) { // ignore the exception } } } // set some headers response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment; filename=" + file.getName()); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Length", Long.toString(rangeFinish - rangeStart + 1)); response.setHeader("Content-Range", "bytes " + rangeStart + "-" + rangeFinish + "/" + fileSize); // seek to the requested offset raf.seek(rangeStart); // send the file byte[] buffer = new byte[4096]; long len; int totalRead = 0; boolean nomore = false; while (true) { len = raf.read(buffer); if (len > 0 && totalRead + len > rangeFinish - rangeStart + 1) { // read more then required? // adjust the length len = rangeFinish - rangeStart + 1 - totalRead; nomore = true; } if (len > 0) { out.write(buffer, 0, (int) len); totalRead += len; if (nomore) { break; } } else { break; } } } finally { raf.close(); } }
From source file:org.apache.jackrabbit.core.data.FileDataStore.java
/** * Set the last modified date of a file, if the file is writable. * * @param file the file//from w ww. ja v a 2 s . co m * @param time the new last modified date * @throws DataStoreException if the file is writable but modifying the date fails */ private static void setLastModified(File file, long time) throws DataStoreException { if (!file.setLastModified(time)) { if (!file.canWrite()) { // if we can't write to the file, so garbage collection will also not delete it // (read only files or file systems) return; } try { // workaround for Windows: if the file is already open for reading // (in this or another process), then setting the last modified date // doesn't work - see also JCR-2872 RandomAccessFile r = new RandomAccessFile(file, "rw"); try { r.setLength(r.length()); } finally { r.close(); } } catch (IOException e) { throw new DataStoreException("An IO Exception occurred while trying to set the last modified date: " + file.getAbsolutePath(), e); } } }
From source file:com.sangupta.snowpack.SnowpackRecover.java
/** * Try and recover from a chunk./*from w ww.j a v a2s . c om*/ * * @param chunkID * @param chunkFile * @param metadataDB * @return * @throws IOException */ private static ChunkInfo recoverChunkInfo(final int chunkID, final File chunkFile, SnowpackMetadataDB metadataDB) throws IOException { // open the file for reading RandomAccessFile raf = new RandomAccessFile(chunkFile, "r"); // read the length first int nameLength, length, terminator, headerLength, numFiles = 0; long offset; List<FlakeMetadata> metas = new ArrayList<FlakeMetadata>(); try { while (raf.getFilePointer() < raf.length()) { offset = raf.getFilePointer(); nameLength = raf.readInt(); byte[] name = new byte[nameLength]; raf.readFully(name); length = raf.readInt(); raf.readLong(); raf.skipBytes((int) length); terminator = raf.readByte(); if (terminator != 0) { System.out.print(" invalid descriptor found..."); return null; } headerLength = 4 + name.length + 4 + 8; numFiles++; metas.add(new FlakeMetadata(new String(name), nameLength, chunkID, offset, headerLength)); } } finally { raf.close(); } // all clear for recovery // save all metadata in new DB for (FlakeMetadata meta : metas) { metadataDB.save(meta); } // return chunk info ChunkInfo info = new ChunkInfo(); info.chunkID = chunkID; info.numFiles = numFiles; info.writePointer = -1; return info; }