Java Code Examples for java.io.RandomAccessFile.getChannel()

The following are Jave code examples for showing how to use getChannel() of the java.io.RandomAccessFile class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: java-learn   File: BasicChannelExample.java   Source Code and License Vote up 7 votes
/**
 * FileChannel 负责文件的读写
 * @throws IOException
 */
public void fileChannelExa() throws IOException {

    String filePath = BasicChannelExample.class.getClassLoader().getResource("data/nio-data.txt").getFile();
    RandomAccessFile aFile = new RandomAccessFile(filePath , "rw");

    FileChannel inChannel = aFile.getChannel();

    ByteBuffer buf = ByteBuffer.allocate(48);

    int bytesRead = inChannel.read(buf);
    while (bytesRead != -1) {

        System.out.println("Read " + bytesRead);
        buf.flip();

        while(buf.hasRemaining()){
            System.out.print((char) buf.get());
        }

        buf.clear();
        bytesRead = inChannel.read(buf);
    }
    aFile.close();
}
 
Example 2
Project: alerta-fraude   File: LocalFilesystem.java   Source Code and License Vote up 6 votes
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
       File file = new File(filesystemPathForURL(inputURL));

       if (!file.exists()) {
           throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
       }

       RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
       try {
           if (raf.length() >= size) {
               FileChannel channel = raf.getChannel();
               channel.truncate(size);
               return size;
           }

           return raf.length();
       } finally {
           raf.close();
       }


}
 
Example 3
Project: GitHub   File: Relay.java   Source Code and License Vote up 6 votes
/**
 * Creates a relay that reads a recorded stream from {@code file}.
 *
 * <p><strong>Warning:</strong> callers to this method must immediately call {@link #newSource} to
 * create a source and close that when they're done. Otherwise a handle to {@code file} will be
 * leaked.
 */
public static Relay read(File file) throws IOException {
  RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
  FileOperator fileOperator = new FileOperator(randomAccessFile.getChannel());

  // Read the header.
  Buffer header = new Buffer();
  fileOperator.read(0, header, FILE_HEADER_SIZE);
  ByteString prefix = header.readByteString(PREFIX_CLEAN.size());
  if (!prefix.equals(PREFIX_CLEAN)) throw new IOException("unreadable cache file");
  long upstreamSize = header.readLong();
  long metadataSize = header.readLong();

  // Read the metadata.
  Buffer metadataBuffer = new Buffer();
  fileOperator.read(FILE_HEADER_SIZE + upstreamSize, metadataBuffer, metadataSize);
  ByteString metadata = metadataBuffer.readByteString();

  // Return the result.
  return new Relay(randomAccessFile, null, upstreamSize, metadata, 0L);
}
 
Example 4
Project: GitHub   File: Relay.java   Source Code and License Vote up 6 votes
/**
 * Creates a relay that reads a recorded stream from {@code file}.
 *
 * <p><strong>Warning:</strong> callers to this method must immediately call {@link #newSource} to
 * create a source and close that when they're done. Otherwise a handle to {@code file} will be
 * leaked.
 */
public static Relay read(File file) throws IOException {
  RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
  FileOperator fileOperator = new FileOperator(randomAccessFile.getChannel());

  // Read the header.
  Buffer header = new Buffer();
  fileOperator.read(0, header, FILE_HEADER_SIZE);
  ByteString prefix = header.readByteString(PREFIX_CLEAN.size());
  if (!prefix.equals(PREFIX_CLEAN)) throw new IOException("unreadable cache file");
  long upstreamSize = header.readLong();
  long metadataSize = header.readLong();

  // Read the metadata.
  Buffer metadataBuffer = new Buffer();
  fileOperator.read(FILE_HEADER_SIZE + upstreamSize, metadataBuffer, metadataSize);
  ByteString metadata = metadataBuffer.readByteString();

  // Return the result.
  return new Relay(randomAccessFile, null, upstreamSize, metadata, 0L);
}
 
Example 5
Project: dataset-lib   File: StreamThread.java   Source Code and License Vote up 6 votes
public ByteBuffer call() throws Exception {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    buff = ByteBuffer.allocate(bufferSize);
    serverSocketChannel.socket().bind(new InetSocketAddress(port));
    while (!stop.isLocked()) {
        RandomAccessFile temp = new RandomAccessFile(tempName, "rw");
        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.read(buff);
        FileChannel channel = temp.getChannel();
        channel.write(buff);
        if (!pause.isLocked()) {
            MappedByteBuffer b = channel.map(MapMode.READ_WRITE, 0, (long) bufferSize);
            b.clear();
        }
        temp.close();
        buff.clear();
    }

    return null;
}
 
Example 6
Project: keemob   File: LocalFilesystem.java   Source Code and License Vote up 6 votes
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
       File file = new File(filesystemPathForURL(inputURL));

       if (!file.exists()) {
           throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
       }

       RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
       try {
           if (raf.length() >= size) {
               FileChannel channel = raf.getChannel();
               channel.truncate(size);
               return size;
           }

           return raf.length();
       } finally {
           raf.close();
       }


}
 
Example 7
Project: Cable-Android   File: TextSecureSessionStore.java   Source Code and License Vote up 6 votes
@Override
public void storeSession(@NonNull SignalProtocolAddress address, @NonNull SessionRecord record) {
  synchronized (FILE_LOCK) {
    try {
      RandomAccessFile sessionFile  = new RandomAccessFile(getSessionFile(address), "rw");
      FileChannel      out          = sessionFile.getChannel();

      out.position(0);
      writeInteger(CURRENT_VERSION, out);
      writeBlob(record.serialize(), out);
      out.truncate(out.position());

      sessionFile.close();
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }
}
 
Example 8
Project: TPlayer   File: FileUtils.java   Source Code and License Vote up 6 votes
public boolean LockExclusive(File targetFile) {

            if (targetFile == null) {
                return false;
            }
            try {
                File lockFile = new File(targetFile.getParentFile().getAbsolutePath().concat("/lock"));
                if (!lockFile.exists()) {
                    lockFile.createNewFile();
                }
                RandomAccessFile randomAccessFile = new RandomAccessFile(lockFile.getAbsolutePath(), "rw");
                FileChannel channel = randomAccessFile.getChannel();
                java.nio.channels.FileLock lock = channel.lock();
                if (!lock.isValid()) {
                    return false;
                }
                RefCntInc(lockFile.getAbsolutePath(), lock, randomAccessFile, channel);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
 
Example 9
Project: siiMobilityAppKit   File: LocalFilesystem.java   Source Code and License Vote up 6 votes
@Override
public long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException {
       File file = new File(filesystemPathForURL(inputURL));

       if (!file.exists()) {
           throw new FileNotFoundException("File at " + inputURL.uri + " does not exist.");
       }

       RandomAccessFile raf = new RandomAccessFile(filesystemPathForURL(inputURL), "rw");
       try {
           if (raf.length() >= size) {
               FileChannel channel = raf.getChannel();
               channel.truncate(size);
               return size;
           }

           return raf.length();
       } finally {
           raf.close();
       }


}
 
Example 10
Project: Breakpoint-http   File: StorageServiceImpl.java   Source Code and License Vote up 5 votes
@Override
public void uploadFileByMappedByteBuffer(MultipartFileParam param) throws IOException {
    String fileName = param.getName();
    String uploadDirPath = finalDirPath + param.getMd5();
    String tempFileName = fileName + "_tmp";
    File tmpDir = new File(uploadDirPath);
    File tmpFile = new File(uploadDirPath, tempFileName);
    if (!tmpDir.exists()) {
        tmpDir.mkdirs();
    }

    RandomAccessFile tempRaf = new RandomAccessFile(tmpFile, "rw");
    FileChannel fileChannel = tempRaf.getChannel();

    //写入该分片数据
    long offset = CHUNK_SIZE * param.getChunk();
    byte[] fileData = param.getFile().getBytes();
    MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, offset, fileData.length);
    mappedByteBuffer.put(fileData);
    // 释放
    FileMD5Util.freedMappedByteBuffer(mappedByteBuffer);
    fileChannel.close();

    boolean isOk = checkAndSetUploadProgress(param, uploadDirPath);
    if (isOk) {
        boolean flag = renameFile(tmpFile, fileName);
        System.out.println("upload complete !!" + flag + " name=" + fileName);
    }
}
 
Example 11
Project: FApkSigner   File: RandomAccessFileDataSink.java   Source Code and License Vote up 5 votes
/**
 * Constructs a new {@code RandomAccessFileDataSink} which stores output starting from the
 * specified position of the provided file.
 */
public RandomAccessFileDataSink(RandomAccessFile file, long startPosition) {
    if (file == null) {
        throw new NullPointerException("file == null");
    }
    if (startPosition < 0) {
        throw new IllegalArgumentException("startPosition: " + startPosition);
    }
    mFile = file;
    mFileChannel = file.getChannel();
    mPosition = startPosition;
}
 
Example 12
Project: incubator-netbeans   File: AbstractLongMap.java   Source Code and License Vote up 5 votes
LongMemoryMappedData(RandomAccessFile file, long length)
          throws IOException {
    FileChannel channel = file.getChannel();
    dumpBuffer = new MappedByteBuffer[(int) (((length + BUFFER_SIZE) - 1) / BUFFER_SIZE)];

    for (int i = 0; i < dumpBuffer.length; i++) {
        long position = i * BUFFER_SIZE;
        long size = Math.min(BUFFER_SIZE + BUFFER_EXT, length - position);
        dumpBuffer[i] = channel.map(MemoryMappedData.MAP_MODE, position, size);
    }

    channel.close();
}
 
Example 13
Project: CryptoKnight   File: FileEncrypt.java   Source Code and License Vote up 5 votes
public static void wipeFile(String file2wipe) throws IOException, FileNotFoundException
{
	File f2w = new File(file2wipe);
	
	 if (f2w.exists())
	 {
		
		SecureRandom sr = new SecureRandom();
		RandomAccessFile raf = new RandomAccessFile(f2w, "rw");
		FileChannel channel = raf.getChannel();
		MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
		
		while (buffer.hasRemaining())
		{
			buffer.put((byte) 0);
		}
		buffer.force();
		buffer.rewind();
		
		while (buffer.hasRemaining())
		{
		    buffer.put((byte) 0xFF);
		}
		buffer.force();
		buffer.rewind();
		
		byte[] data = new byte[1];
		while (buffer.hasRemaining())
		{
		    sr.nextBytes(data);
		    buffer.put(data[0]);
		}
		buffer.force();
	    raf.close();
		f2w.delete(); 
	 }
}
 
Example 14
Project: dble   File: FileNio.java   Source Code and License Vote up 5 votes
FileNio(String fileName, String mode) throws IOException {
    this.name = fileName;
    RandomAccessFile file = new RandomAccessFile(fileName, mode);
    this.channel = file.getChannel();
    this.fileLength = DbleServer.getInstance().getConfig().getSystem().getMappedFileSize();
    this.pos = 0;
}
 
Example 15
Project: incubator-ratis   File: LogOutputStream.java   Source Code and License Vote up 5 votes
public LogOutputStream(File file, boolean append, long segmentMaxSize,
    long preallocatedSize, int bufferSize)
    throws IOException {
  this.file = file;
  this.checksum = new PureJavaCrc32C();
  this.segmentMaxSize = segmentMaxSize;
  this.preallocatedSize = preallocatedSize;
  RandomAccessFile rp = new RandomAccessFile(file, "rw");
  fc = rp.getChannel();
  fc.position(fc.size());
  preallocatedPos = fc.size();
  out = new BufferedWriteChannel(fc, bufferSize);

  try {
    fc = rp.getChannel();
    fc.position(fc.size());
    preallocatedPos = fc.size();

    out = new BufferedWriteChannel(fc, bufferSize);
    if (!append) {
      create();
    }
  } catch (IOException ioe) {
    LOG.warn("Hit IOException while creating log segment " + file
        + ", delete the partial file.");
    // hit IOException, clean up the in-progress log file
    try {
      FileUtils.deleteFully(file);
    } catch (IOException e) {
      LOG.warn("Failed to delete the file " + file, e);
    }
    throw ioe;
  }
}
 
Example 16
Project: alfresco-repository   File: FileContentWriter.java   Source Code and License Vote up 5 votes
@Override
protected WritableByteChannel getDirectWritableChannel() throws ContentIOException
{
    try
    {
        // we may not write to an existing file - EVER!!
        if (file.exists() && file.length() > 0)
        {
            throw new IOException("File exists - overwriting not allowed");
        }
        // create the channel
        WritableByteChannel channel = null;
        if (allowRandomAccess)
        {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");  // will create it
            channel = randomAccessFile.getChannel();
        }
        else
        {
            OutputStream os = new FileOutputStream(file);
            channel = Channels.newChannel(os);
        }
        // done
        if (logger.isDebugEnabled())
        {
            logger.debug("Opened write channel to file: \n" +
                    "   file: " + file + "\n" +
                    "   random-access: " + allowRandomAccess);
        }
        return channel;
    }
    catch (Throwable e)
    {
        throw new ContentIOException("Failed to open file channel: " + this, e);
    }
}
 
Example 17
Project: microservices-sample-project   File: LocalStorageImageUtil.java   Source Code and License Vote up 5 votes
@Override
public ResponseEntity<StreamingResponseBody> readFile(String fileLocation, String imageDir, String id,
		String fileName) {
	StreamingResponseBody streamingResponseBody = new StreamingResponseBody() {

		@Override
		public void writeTo(OutputStream outputStream) {
			try {

				String fileStr = fileLocation + File.separator + imageDir + File.separator + id + File.separator
						+ fileName;

				RandomAccessFile file = new RandomAccessFile(fileStr, "r");
				FileChannel inChannel = file.getChannel();
				ByteBuffer buffer = ByteBuffer.allocate(1024);
				while (inChannel.read(buffer) > 0) {
					buffer.flip();
					for (int i = 0; i < buffer.limit(); i++) {
						outputStream.write(buffer.get());
					}
					buffer.clear();
					outputStream.flush();
				}
				inChannel.close();
				file.close();

			} catch (IOException e) {
				logger.error("Image Not Found : error " + e.getMessage());
				throw new ResourceNotFoundException("Image Not Found : " + id + "/" + fileName);
			}
		}
	};

	HttpHeaders headers = new HttpHeaders();
	headers.add(HttpHeaders.CONTENT_TYPE, "image/*");
	return new ResponseEntity<StreamingResponseBody>(streamingResponseBody, headers, HttpStatus.OK);
}
 
Example 18
Project: flume-release-1.7.0   File: FlumeEventQueue.java   Source Code and License Vote up 4 votes
/**
 * Serialize the set of in flights into a byte longBuffer.
 *
 * @return Returns the checksum of the buffer that is being
 * asynchronously written to disk.
 */
public void serializeAndWrite() throws Exception {
  Collection<Long> values = inflightEvents.values();
  if (!fileChannel.isOpen()) {
    file = new RandomAccessFile(inflightEventsFile, "rw");
    fileChannel = file.getChannel();
  }
  if (values.isEmpty()) {
    file.setLength(0L);
  }
  //What is written out?
  //Checksum - 16 bytes
  //and then each key-value pair from the map:
  //transactionid numberofeventsforthistxn listofeventpointers

  try {
    int expectedFileSize = (((inflightEvents.keySet().size() * 2) //for transactionIDs and
                                                                  //events per txn ID
        + values.size()) * 8) //Event pointers
        + 16; //Checksum
    //There is no real need of filling the channel with 0s, since we
    //will write the exact number of bytes as expected file size.
    file.setLength(expectedFileSize);
    Preconditions.checkState(file.length() == expectedFileSize,
        "Expected File size of inflight events file does not match the "
            + "current file size. Checkpoint is incomplete.");
    file.seek(0);
    final ByteBuffer buffer = ByteBuffer.allocate(expectedFileSize);
    LongBuffer longBuffer = buffer.asLongBuffer();
    for (Long txnID : inflightEvents.keySet()) {
      Set<Long> pointers = inflightEvents.get(txnID);
      longBuffer.put(txnID);
      longBuffer.put((long) pointers.size());
      LOG.debug("Number of events inserted into "
          + "inflights file: " + String.valueOf(pointers.size())
          + " file: " + inflightEventsFile.getCanonicalPath());
      long[] written = ArrayUtils.toPrimitive(
          pointers.toArray(new Long[0]));
      longBuffer.put(written);
    }
    byte[] checksum = digest.digest(buffer.array());
    file.write(checksum);
    buffer.position(0);
    fileChannel.write(buffer);
    fileChannel.force(true);
    syncRequired = false;
  } catch (IOException ex) {
    LOG.error("Error while writing checkpoint to disk.", ex);
    throw ex;
  }
}
 
Example 19
Project: openjdk-jdk10   File: ExpandingMap.java   Source Code and License Vote up 4 votes
public static void main(String[] args) throws Exception {

        int initialSize = 20480*1024;
        int maximumMapSize = 16*1024*1024;
        int maximumFileSize = 300000000;

        File file = File.createTempFile("exp", "tmp");
        file.deleteOnExit();
        RandomAccessFile f = new RandomAccessFile(file, "rw");
        f.setLength(initialSize);

        FileChannel fc = f.getChannel();

        ByteBuffer[] buffers = new ByteBuffer[128];

        System.out.format("map %d -> %d\n", 0, initialSize);
        buffers[0] = fc.map(FileChannel.MapMode.READ_WRITE, 0, initialSize);

        int currentBuffer = 0;
        int currentSize = initialSize;
        int currentPosition = 0;

        ArrayList<String> junk = new ArrayList<String>();

        while (currentPosition+currentSize < maximumFileSize) {
            int inc = Math.max(1000*1024, (currentPosition+currentSize)/8);

            int size = currentPosition+currentSize+inc;
            f.setLength(size);

            while (currentSize+inc > maximumMapSize) {
                if (currentSize < maximumMapSize) {
                    System.out.format("map %d -> %d\n", currentPosition,
                        (currentPosition + maximumMapSize));
                    buffers[currentBuffer] = fc.map(FileChannel.MapMode.READ_WRITE,
                        currentPosition, maximumMapSize);
                    fillBuffer(buffers[currentBuffer], currentSize);
                }
                currentPosition += maximumMapSize;
                inc = currentSize+inc-maximumMapSize;
                currentSize = 0;
                currentBuffer++;
                if (currentBuffer == buffers.length) {
                    ByteBuffer[] old = buffers;
                    buffers = new ByteBuffer[currentBuffer+currentBuffer/2];
                    System.arraycopy(old, 0, buffers, 0, currentBuffer);                                        }
            }
            currentSize += inc;
            if (currentSize > 0) {
                System.out.format("map %d -> %d\n", currentPosition,
                    (currentPosition + currentSize));
                buffers[currentBuffer] = fc.map(FileChannel.MapMode.READ_WRITE,
                     currentPosition, currentSize);
                fillBuffer(buffers[currentBuffer], currentSize-inc);
            }

            // busy loop needed to reproduce issue
            long t = System.currentTimeMillis();
            while (System.currentTimeMillis() < t+500) {
                junk.add(String.valueOf(t));
                if (junk.size() > 100000) junk.clear();
            }
        }

        fc.close();
        // cleanup the ref to mapped buffers so they can be GCed
        for (int i = 0; i < buffers.length; i++)
            buffers[i] = null;
        System.gc();
        // Take a nap to wait for the Cleaner to cleanup those unrefed maps
        Thread.sleep(1000);
        System.out.println("TEST PASSED");
    }
 
Example 20
Project: MetadataEditor   File: Mp4StcoBox.java   Source Code and License Vote up 4 votes
public static Mp4StcoBox getStco(RandomAccessFile raf) throws IOException, CannotReadException
{
    FileChannel fc = raf.getChannel();
    Mp4BoxHeader moovHeader = Mp4BoxHeader.seekWithinLevel(fc, Mp4AtomIdentifier.MOOV.getFieldName());
    if (moovHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }
    ByteBuffer moovBuffer = ByteBuffer.allocate(moovHeader.getLength() - Mp4BoxHeader.HEADER_LENGTH);
    fc.read(moovBuffer);
    moovBuffer.rewind();

    //Level 2-Searching for "mvhd" somewhere within "moov", we make a slice after finding header
    //so all getFields() methods will be relative to mvdh positions
    Mp4BoxHeader boxHeader = Mp4BoxHeader.seekWithinLevel(moovBuffer, Mp4AtomIdentifier.MVHD.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }
    ByteBuffer mvhdBuffer = moovBuffer.slice();
    Mp4MvhdBox mvhd = new Mp4MvhdBox(boxHeader, mvhdBuffer);
    mvhdBuffer.position(mvhdBuffer.position() + boxHeader.getDataLength());

    //Level 2-Searching for "trak" within "moov"
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.TRAK.getFieldName());
    int endOfFirstTrackInBuffer = mvhdBuffer.position() + boxHeader.getDataLength();

    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }
    //Level 3-Searching for "mdia" within "trak"
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.MDIA.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }

    //Level 4-Searching for "mdhd" within "mdia"
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.MDHD.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }

    //Level 4-Searching for "minf" within "mdia"
    mvhdBuffer.position(mvhdBuffer.position() + boxHeader.getDataLength());
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.MINF.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }

    //Level 5-Searching for "smhd" within "minf"
    //Only an audio track would have a smhd frame
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.SMHD.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }
    mvhdBuffer.position(mvhdBuffer.position() + boxHeader.getDataLength());

    //Level 5-Searching for "stbl within "minf"
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.STBL.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }

    //Level 6-Searching for "stco within "stbl"
    boxHeader = Mp4BoxHeader.seekWithinLevel(mvhdBuffer, Mp4AtomIdentifier.STCO.getFieldName());
    if (boxHeader == null)
    {
        throw new CannotReadException("This file does not appear to be an audio file");
    }
    Mp4StcoBox stco = new Mp4StcoBox(boxHeader, mvhdBuffer);
    return stco;
}