List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
From source file:com.slytechs.capture.FileFactory.java
public FormatType formatType(final File file) throws IOException { try {// www . j a v a2 s . com new PcapFileCapture(file, FileMode.ReadOnlyNoMap, null).close(); if (logger.isTraceEnabled()) { logger.trace(file.getName() + ", type=" + FormatType.Pcap); } return FormatType.Pcap; } catch (final Exception e) { } try { new SnoopFileCapture(file, FileMode.ReadOnlyNoMap, null).close(); if (logger.isTraceEnabled()) { logger.trace(file.getName() + ", type=" + FormatType.Pcap); } return FormatType.Snoop; } catch (final Exception e) { } /* * Now try InputCapture which may also yield a known format */ ReadableByteChannel channel = new RandomAccessFile(file, "r").getChannel(); FormatType type = formatType(channel); channel.close(); if (logger.isTraceEnabled()) { logger.trace(file.getName() + ", type=" + FormatType.Pcap); } return type; }
From source file:dbseer.comp.process.live.LogTailer.java
@Override public void run() { RandomAccessFile reader = null; try {/*from w w w.j av a 2 s .c o m*/ long last = 0; // The last time the file was checked for changes long position = 0; // position within the file // Open the file while (run && reader == null) { try { reader = new RandomAccessFile(file, RAF_MODE); } catch (FileNotFoundException e) { listener.fileNotFound(); } if (reader == null) { try { Thread.sleep(delayMillis); } catch (InterruptedException e) { } } else { // The current position in the file // position = (startOffset > file.length()) ? file.length() : startOffset; if (startOffset == -1) { position = file.length(); } else { position = startOffset; } last = System.currentTimeMillis(); reader.seek(position); } } while (run) { boolean newer = FileUtils.isFileNewer(file, last); // IO-279, must be done first // Check the file length to see if it was rotated long length = file.length(); if (length < position) { // File was rotated listener.fileRotated(); // Reopen the reader after rotation try { // Ensure that the old file is closed iff we re-open it successfully RandomAccessFile save = reader; reader = new RandomAccessFile(file, RAF_MODE); position = 0; // close old file explicitly rather than relying on GC picking up previous RAF IOUtils.closeQuietly(save); } catch (FileNotFoundException e) { // in this case we continue to use the previous reader and position values listener.fileNotFound(); } continue; } else { // File was not rotated // See if the file needs to be read again if (length > position) { // The file has more content than it did last time position = readLines(reader); last = System.currentTimeMillis(); } else if (newer) { /* * This can happen if the file is truncated or overwritten with the exact same length of * information. In cases like this, the file position needs to be reset */ if (resetFilePositionIfOverwrittenWithTheSameLength) { position = 0; reader.seek(position); // cannot be null here // Now we can read new lines position = readLines(reader); last = System.currentTimeMillis(); } } else { Thread.sleep(DEFAULT_DELAY_MILLIS); } } } } catch (Exception e) { listener.handle(e); } finally { IOUtils.closeQuietly(reader); } }
From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java
/** * Opens file to write a 7z archive to./*from www . jav a 2 s . co m*/ * * @param filename name of the file to write to * @throws IOException if opening the file fails */ public SevenZOutputFile(final File filename) throws IOException { file = new RandomAccessFile(filename, "rw"); file.seek(SevenZFile.SIGNATURE_HEADER_SIZE); }
From source file:com.owncloud.android.oc_framework.network.webdav.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;/*from w w w . ja v a2s . c om*/ try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getName()); } } } } catch (IOException io) { Log.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }
From source file:eu.alefzero.webdav.FileRequestEntity.java
@Override public void writeRequest(final OutputStream out) throws IOException { //byte[] tmp = new byte[4096]; ByteBuffer tmp = ByteBuffer.allocate(4096); int readResult = 0; // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it // globally in some fashionable manner RandomAccessFile raf = new RandomAccessFile(mFile, "r"); FileChannel channel = raf.getChannel(); Iterator<OnDatatransferProgressListener> it = null; long transferred = 0; long size = mFile.length(); if (size == 0) size = -1;//from w w w .ja v a 2s . c o m try { while ((readResult = channel.read(tmp)) >= 0) { out.write(tmp.array(), 0, readResult); tmp.clear(); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next().onTransferProgress(readResult, transferred, size, mFile.getName()); } } } } catch (IOException io) { Log_OC.e("FileRequestException", io.getMessage()); throw new RuntimeException( "Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); } finally { channel.close(); raf.close(); } }
From source file:com.haulmont.cuba.core.sys.LogControlImpl.java
@Override public String getTail(String fileName) throws LogControlException { // security check, supported only valid file names fileName = FilenameUtils.getName(fileName); StringBuilder sb = new StringBuilder(); RandomAccessFile randomAccessFile = null; try {//w w w. java2 s . co m File logFile = new File(logDir, fileName); if (!logFile.exists()) throw new LogFileNotFoundException(fileName); randomAccessFile = new RandomAccessFile(logFile, "r"); long lengthFile = randomAccessFile.length(); if (lengthFile >= LOG_TAIL_AMOUNT_BYTES) { randomAccessFile.seek(lengthFile - LOG_TAIL_AMOUNT_BYTES); skipFirstLine(randomAccessFile); } while (randomAccessFile.read() != -1) { randomAccessFile.seek(randomAccessFile.getFilePointer() - 1); String line = readUtf8Line(randomAccessFile); if (line != null) { sb.append(line).append("\n"); } } } catch (IOException e) { log.error("Error reading log file", e); throw new LogControlException("Error reading log file: " + fileName); } finally { if (randomAccessFile != null) { try { randomAccessFile.close(); } catch (IOException ignored) { } } } return sb.toString(); }
From source file:com.sc.l45.weblogviewer.reader.ReversedLinesFileReaderLineSeparator.java
/** * Creates a ReversedLinesFileReader with the given block size and encoding. * * @param file/*from w w w .ja v a2s . c o m*/ * the file to be read * @param blockSize * size of the internal buffer (for ideal performance this should * match with the block size of the underlying file system). * @param encoding * the encoding of the file * @throws IOException if an I/O error occurs * @since 2.3 */ public ReversedLinesFileReaderLineSeparator(final File file, final int blockSize, final Charset encoding) throws IOException { this.blockSize = blockSize; this.encoding = encoding; randomAccessFile = new RandomAccessFile(file, "r"); totalByteLength = randomAccessFile.length(); int lastBlockLength = (int) (totalByteLength % blockSize); if (lastBlockLength > 0) { totalBlockCount = totalByteLength / blockSize + 1; } else { totalBlockCount = totalByteLength / blockSize; if (totalByteLength > 0) { lastBlockLength = blockSize; } } currentFilePart = new FilePart(totalBlockCount, lastBlockLength, null); // --- check & prepare encoding --- Charset charset = Charsets.toCharset(encoding); CharsetEncoder charsetEncoder = charset.newEncoder(); float maxBytesPerChar = charsetEncoder.maxBytesPerChar(); if (maxBytesPerChar == 1f) { // all one byte encodings are no problem byteDecrement = 1; } else if (charset == Charset.forName("UTF-8")) { // UTF-8 works fine out of the box, for multibyte sequences a second UTF-8 byte can never be a newline byte // http://en.wikipedia.org/wiki/UTF-8 byteDecrement = 1; } else if (charset == Charset.forName("Shift_JIS")) { // Same as for UTF-8 // http://www.herongyang.com/Unicode/JIS-Shift-JIS-Encoding.html byteDecrement = 1; } else if (charset == Charset.forName("UTF-16BE") || charset == Charset.forName("UTF-16LE")) { // UTF-16 new line sequences are not allowed as second tuple of four byte sequences, // however byte order has to be specified byteDecrement = 2; } else if (charset == Charset.forName("UTF-16")) { throw new UnsupportedEncodingException( "For UTF-16, you need to specify the byte order (use UTF-16BE or UTF-16LE)"); } else { throw new UnsupportedEncodingException( "Encoding " + encoding + " is not supported yet (feel free to submit a patch)"); } // NOTE: The new line sequences are matched in the order given, so it is important that \r\n is BEFORE \n newLineSequences = new byte[][] { "\r\n".getBytes(encoding), "\n".getBytes(encoding), "\r".getBytes(encoding) }; avoidNewlineSplitBufferSize = newLineSequences[0].length; }
From source file:com.adaptris.core.fs.enhanced.FileSorterCase.java
private void ensureSize(long size, File f) throws IOException { RandomAccessFile rf = new RandomAccessFile(f, "rw"); rf.setLength(size);/*from w w w .j a v a2 s .c om*/ rf.close(); }
From source file:test.other.T_DaoTest.java
public void test2() throws SQLException, IOException { System.out.println(System.nanoTime() / 1000000); ResultSet rs = conn.createStatement().executeQuery("select content from fc_Post where id = 15"); rs.next();//from w w w .j a v a 2 s .c o m String text = rs.getString(1); System.out.println(text.length()); System.out.println(System.nanoTime() / 1000000); @SuppressWarnings("resource") FileChannel rwChannel = new RandomAccessFile("textfile.txt", "rw").getChannel(); ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, text.length() + 10); int lg = text.length() / 1000000; int pos = 0; byte[] buf = new byte[text.length() / 1000000]; System.out.println(System.nanoTime() / 1000000); for (int i = 0; i < 1000000; i++) { System.arraycopy(text.getBytes(), pos, buf, 0, lg); wrBuf.put(buf); pos += lg; } System.out.println(System.nanoTime() / 1000000); rwChannel.close(); }
From source file:com.taobao.common.tfs.impl.GcWorker.java
private void doGc(SegmentInfoContainer segmentInfoContainer, File[] fileList) { for (File file : fileList) { if (file.length() == 0) { log.info("expired gc file is empty, unlink. " + file.getAbsolutePath()); file.delete();//from w w w. j a v a 2 s. c om continue; } String fileName = file.getAbsolutePath(); log.info("do gc filename " + fileName); int serverIdIndex = fileName.lastIndexOf('!'); if (serverIdIndex == -1) { log.error("file name is invalid, no server id: " + fileName); // unlink ? continue; } FileLock fileLock = null; try { FileChannel fileChannel = (new RandomAccessFile(file, "rw")).getChannel(); fileLock = fileChannel.tryLock(); if (fileLock == null) { log.warn("file: " + fileName + " is busy, maybe another gc worker is working over it"); continue; } long serverId = Long.parseLong(fileName.substring(serverIdIndex + 1)); segmentInfoContainer.loadFile(fileName); Collection<SegmentInfo> segmentInfos = segmentInfoContainer.getSegmentInfos(); for (SegmentInfo segmentInfo : segmentInfos) { if (tfsManager.unlinkFile(segmentInfo.getBlockId(), segmentInfo.getFileId(), serverId)) { log.info("gc success. blockId: " + segmentInfo.getBlockId() + " fileId: " + segmentInfo.getFileId() + " serverId: " + serverId); } else { log.error("gc fail. blockId: " + segmentInfo.getFileId() + " fileId: " + segmentInfo.getFileId() + " serverId: " + serverId); } } } catch (Exception e) { log.warn("", e); } finally { try { if (fileLock != null) { fileLock.release(); } segmentInfoContainer.cleanUp(); // delete anyway file.delete(); } catch (Exception e) { log.warn("filelock realse fail.", e); } } } }