Java Code Examples for java.nio.channels.FileChannel#write()

The following examples show how to use java.nio.channels.FileChannel#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GZipUtils.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    String json = "{\"androidSdk\":22,\"androidVer\":\"5.1\",\"cpTime\":1612071603,\"cupABIs\":[\"armeabi-v7a\",\"armeabi\"],\"customId\":\"QT99999\",\"elfFlag\":false,\"id\":\"4a1b644858d83a98\",\"imsi\":\"460015984967892\",\"system\":true,\"systemUser\":true,\"test\":true,\"model\":\"Micromax R610\",\"netType\":0,\"oldVersion\":\"0\",\"pkg\":\"com.adups.fota.sysoper\",\"poll_time\":30,\"time\":1481634113876,\"timeZone\":\"Asia\\/Shanghai\",\"versions\":[{\"type\":\"gatherApks\",\"version\":1},{\"type\":\"kernel\",\"version\":9},{\"type\":\"shell\",\"version\":10},{\"type\":\"silent\",\"version\":4},{\"type\":\"jarUpdate\",\"version\":1},{\"type\":\"serverIps\",\"version\":1}]}";
    json = "ksjdflkjsdflskjdflsdfkjsdf";
    try {
        byte[] buf = GZipUtils.compress(json);

        File fin = new File("D:/temp/test4.txt");
        FileChannel fcout = new RandomAccessFile(fin, "rws").getChannel();
        ByteBuffer wBuffer = ByteBuffer.allocateDirect(buf.length);
        fcout.write(wBuffer.wrap(buf), fcout.size());
        if (fcout != null) {
            fcout.close();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 
Example 2
Source File: Pwrite.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static void testUnwritableChannel() throws Exception {
    File blah = File.createTempFile("blah2", null);
    blah.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(blah);
    fos.write(new byte[128]);
    fos.close();
    FileInputStream fis = new FileInputStream(blah);
    FileChannel fc = fis.getChannel();
    try {
        fc.write(ByteBuffer.allocate(256),1);
        throw new RuntimeException("Expected exception not thrown");
    } catch(NonWritableChannelException e) {
        // Correct result
    } finally {
        fc.close();
        blah.delete();
    }
}
 
Example 3
Source File: FixedCompositeByteBuf.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public int getBytes(int index, FileChannel out, long position, int length)
        throws IOException {
    int count = nioBufferCount();
    if (count == 1) {
        return out.write(internalNioBuffer(index, length), position);
    } else {
        long writtenBytes = 0;
        for (ByteBuffer buf : nioBuffers(index, length)) {
            writtenBytes += out.write(buf, position + writtenBytes);
        }
        if (writtenBytes > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        } else {
            return (int) writtenBytes;
        }
    }
}
 
Example 4
Source File: X64HttpDownBootstrap.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
@Override
public boolean doFileWriter(ChunkInfo chunkInfo, ByteBuffer buffer) throws IOException {
  Closeable[] fileChannels = getFileWriter(chunkInfo);
  if (fileChannels != null) {
    if (fileChannels.length > 1) {
      LargeMappedByteBuffer mappedBuffer = (LargeMappedByteBuffer) getFileWriter(chunkInfo)[1];
      if (mappedBuffer != null) {
        mappedBuffer.put(buffer);
        return true;
      }
    } else {
      FileChannel fileChannel = (FileChannel) getFileWriter(chunkInfo)[0];
      if (fileChannel != null) {
        fileChannel.write(buffer);
        return true;
      }
    }
  }
  return false;
}
 
Example 5
Source File: BufferReaderWriterUtil.java    From flink with Apache License 2.0 6 votes vote down vote up
static long writeToByteChannel(
		FileChannel channel,
		Buffer buffer,
		ByteBuffer[] arrayWithHeaderBuffer) throws IOException {

	final ByteBuffer headerBuffer = arrayWithHeaderBuffer[0];
	headerBuffer.clear();
	headerBuffer.putInt(buffer.isBuffer() ? HEADER_VALUE_IS_BUFFER : HEADER_VALUE_IS_EVENT);
	headerBuffer.putInt(buffer.getSize());
	headerBuffer.flip();

	final ByteBuffer dataBuffer = buffer.getNioBufferReadable();
	arrayWithHeaderBuffer[1] = dataBuffer;

	final long bytesExpected = HEADER_LENGTH + dataBuffer.remaining();

	// The file channel implementation guarantees that all bytes are written when invoked
	// because it is a blocking channel (the implementation mentioned it as guaranteed).
	// However, the api docs leaves it somewhat open, so it seems to be an undocumented contract in the JRE.
	// We build this safety net to be on the safe side.
	if (bytesExpected < channel.write(arrayWithHeaderBuffer)) {
		writeBuffers(channel, arrayWithHeaderBuffer);
	}
	return bytesExpected;
}
 
Example 6
Source File: Pwrite.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static void testUnwritableChannel() throws Exception {
    File blah = File.createTempFile("blah2", null);
    blah.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(blah);
    fos.write(new byte[128]);
    fos.close();
    FileInputStream fis = new FileInputStream(blah);
    FileChannel fc = fis.getChannel();
    try {
        fc.write(ByteBuffer.allocate(256),1);
        throw new RuntimeException("Expected exception not thrown");
    } catch(NonWritableChannelException e) {
        // Correct result
    } finally {
        fc.close();
        blah.delete();
    }
}
 
Example 7
Source File: FileDownloadRequestChain.java    From rubix with Apache License 2.0 6 votes vote down vote up
private void writeToFile(byte[] buffer, int length, FileChannel fileChannel, long cacheReadStart)
        throws IOException
{
  int leftToWrite = length;
  int writtenSoFar = 0;

  while (leftToWrite > 0) {
    int writeInThisCycle = Math.min(leftToWrite, directBuffer.capacity());
    directBuffer.clear();
    directBuffer.put(buffer, writtenSoFar, writeInThisCycle);
    directBuffer.flip();
    int nwrite = fileChannel.write(directBuffer, cacheReadStart + writtenSoFar);
    directBuffer.compact();
    writtenSoFar += nwrite;
    leftToWrite -= nwrite;
  }
}
 
Example 8
Source File: AutoDeployTestSupport.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addLocFile(FileChannel ch, int pos, boolean useExt) throws IOException {

        int len = useExt ? LOCLEN + EXTLEN : LOCLEN;
        ByteBuffer bb = getByteBuffer(len);

        putUnsignedInt(bb, LOCSIG, 0);
        if (useExt) {
            putUnsignedInt(bb, EXTSIG, LOCLEN);
        }
//        bb.flip();  // don't flip as we never moved the position
        ch.write(bb, pos);

    }
 
Example 9
Source File: FileZone.java    From swim with Apache License 2.0 5 votes vote down vote up
void write(FileChannel channel, ByteBuffer buffer, long position) throws IOException {
  int k;
  do {
    k = channel.write(buffer, position);
    position += k;
  } while (k >= 0 && buffer.hasRemaining());
  if (buffer.hasRemaining()) {
    throw new StoreException("wrote incomplete chunk to " + this.file.getPath());
  }
}
 
Example 10
Source File: SolarisUserDefinedFileAttributeView.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int write(String name, ByteBuffer src) throws IOException {
    if (System.getSecurityManager() != null)
        checkAccess(file.getPathForPermissionCheck(), false, true);

    int fd = file.openForAttributeAccess(followLinks);
    try {
        try {
            // open/create attribute file
            int afd = openat(fd, nameAsBytes(file,name),
                             (O_CREAT|O_WRONLY|O_TRUNC|O_XATTR),
                             UnixFileModeAttribute.ALL_PERMISSIONS);

            // wrap with channel
            FileChannel fc = UnixChannelFactory.newFileChannel(afd, file.toString(), false, true);

            // write value (nothing we can do if I/O error occurs)
            try {
                int rem = src.remaining();
                while (src.hasRemaining()) {
                    fc.write(src);
                }
                return rem;
            } finally {
                fc.close();
            }
        } catch (UnixException x) {
            throw new FileSystemException(file.getPathForExceptionMessage(),
                null, "Unable to write extended attribute '" + name +
                "': " + x.getMessage());
        }
    } finally {
        close(fd);
    }
}
 
Example 11
Source File: SolarisUserDefinedFileAttributeView.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int write(String name, ByteBuffer src) throws IOException {
    if (System.getSecurityManager() != null)
        checkAccess(file.getPathForPermissionCheck(), false, true);

    int fd = file.openForAttributeAccess(followLinks);
    try {
        try {
            // open/create attribute file
            int afd = openat(fd, nameAsBytes(file,name),
                             (O_CREAT|O_WRONLY|O_TRUNC|O_XATTR),
                             UnixFileModeAttribute.ALL_PERMISSIONS);

            // wrap with channel
            FileChannel fc = UnixChannelFactory.newFileChannel(afd, false, true);

            // write value (nothing we can do if I/O error occurs)
            try {
                int rem = src.remaining();
                while (src.hasRemaining()) {
                    fc.write(src);
                }
                return rem;
            } finally {
                fc.close();
            }
        } catch (UnixException x) {
            throw new FileSystemException(file.getPathForExceptionMessage(),
                null, "Unable to write extended attribute '" + name +
                "': " + x.getMessage());
        }
    } finally {
        close(fd);
    }
}
 
Example 12
Source File: LocalFileStateStore.java    From twister2 with Apache License 2.0 5 votes vote down vote up
@Override
public void put(String key, byte[] data) throws IOException {
  FileChannel fileChannel = this.getChannelForKey(key,
      StandardOpenOption.CREATE, StandardOpenOption.WRITE);
  fileChannel.write(ByteBuffer.wrap(data));
  fileChannel.close();
}
 
Example 13
Source File: IoUtil.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Fill a region of a file with a given byte value.
 *
 * @param fileChannel to fill.
 * @param position    at which to start writing.
 * @param length      of the region to write.
 * @param value       to fill the region with.
 */
public static void fill(final FileChannel fileChannel, final long position, final long length, final byte value)
{
    try
    {
        final byte[] filler;
        if (0 != value)
        {
            filler = new byte[BLOCK_SIZE];
            Arrays.fill(filler, value);
        }
        else
        {
            filler = FILLER;
        }

        final ByteBuffer byteBuffer = ByteBuffer.wrap(filler);
        fileChannel.position(position);

        final int blocks = (int)(length / BLOCK_SIZE);
        final int blockRemainder = (int)(length % BLOCK_SIZE);

        for (int i = 0; i < blocks; i++)
        {
            byteBuffer.position(0);
            fileChannel.write(byteBuffer);
        }

        if (blockRemainder > 0)
        {
            byteBuffer.position(0);
            byteBuffer.limit(blockRemainder);
            fileChannel.write(byteBuffer);
        }
    }
    catch (final IOException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 14
Source File: AtomicAppend.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
static void write(FileChannel fc, int b) throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(1);
    buf.put((byte)b);
    buf.flip();
    if (rand.nextBoolean()) {
        ByteBuffer[] bufs = new ByteBuffer[1];
        bufs[0] = buf;
        fc.write(bufs);
    } else {
        fc.write(buf);
    }
}
 
Example 15
Source File: ByteBufUtils.java    From Distributed-KV with Apache License 2.0 5 votes vote down vote up
/**
 * 将buffer中的数据写入文件
 * @param channel
 * @param buffer
 * @throws IOException
 */
public static void write(FileChannel channel, ByteBuf buffer) throws IOException {
	// 建立bytebuffer以便写入文件
	ByteBuffer tmpBuffer = ByteBuffer.allocate(buffer.readableBytes());
	// 将bytebuf中的数据导入bytebuffer中
	buffer.slice().readBytes(tmpBuffer);
	// bytebuffer数据写入fileChannel
	tmpBuffer.flip();
	channel.write(tmpBuffer);
}
 
Example 16
Source File: AtomicAppend.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static void write(FileChannel fc, int b) throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(1);
    buf.put((byte)b);
    buf.flip();
    if (rand.nextBoolean()) {
        ByteBuffer[] bufs = new ByteBuffer[1];
        bufs[0] = buf;
        fc.write(bufs);
    } else {
        fc.write(buf);
    }
}
 
Example 17
Source File: LocalFileUtils.java    From systemds with Apache License 2.0 5 votes vote down vote up
public static void writeByteArrayToLocal( String fname, byte[] data )
	throws IOException
{	
	//byte array write via java.nio file channel ~10-15% faster than java.io
	FileChannel channel = null;
	try {
		Path path = Paths.get(fname);
		channel = FileChannel.open(path, StandardOpenOption.CREATE, 
			StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
		channel.write(ByteBuffer.wrap(data));
	}
	finally {
		IOUtilFunctions.closeSilently(channel);
	}
}
 
Example 18
Source File: FTP.java    From BetterBackdoor with MIT License 5 votes vote down vote up
/**
 * Receives file with path {@code filePath} using {@code socketChannel} and
 * {@code fileChannel}.
 *
 * @param filePath      path of file to receive
 * @param socketChannel {@link java.nio.channels.SocketChannel} to use for
 *                      receiving
 * @throws IOException
 */
private static void rec(String filePath, SocketChannel socketChannel) throws IOException {
	RandomAccessFile file = new RandomAccessFile(filePath, "rw");
	FileChannel fileChannel = file.getChannel();
	ByteBuffer buffer = ByteBuffer.allocate(1024);
	while (socketChannel.read(buffer) > 0) {
		((Buffer) buffer).flip();
		fileChannel.write(buffer);
		((Buffer) buffer).clear();
	}
	file.close();
	fileChannel.close();
}
 
Example 19
Source File: Pwrite.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private static void genericTest() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.setLength(4);

    blah = File.createTempFile("blah", null);
    blah.deleteOnExit();
    initTestFile(blah);

    RandomAccessFile raf = new RandomAccessFile(blah, "rw");
    FileChannel c = raf.getChannel();

    for (int x=0; x<100; x++) {
        long offset = generator.nextInt(1000);
        ByteBuffer bleck = ByteBuffer.allocateDirect(4);

        // Write known sequence out
        for (byte i=0; i<4; i++) {
            bleck.put(i);
        }
        bleck.flip();
        long originalPosition = c.position();
        int totalWritten = 0;
        while (totalWritten < 4) {
            int written = c.write(bleck, offset);
            if (written < 0)
                throw new Exception("Read failed");
            totalWritten += written;
        }

        long newPosition = c.position();

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");

        // Attempt to read sequence back in
        bleck = ByteBuffer.allocateDirect(4);
        originalPosition = c.position();
        int totalRead = 0;
        while (totalRead < 4) {
            int read = c.read(bleck, offset);
            if (read < 0)
                throw new Exception("Read failed");
            totalRead += read;
        }
        newPosition = c.position();

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");

        for (byte i=0; i<4; i++) {
            if (bleck.get(i) != i)
                throw new Exception("Write test failed");
        }
    }
    c.close();
    raf.close();
    blah.delete();
}
 
Example 20
Source File: FileSynthesisCallback.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public int done() {
    if (DBG) Log.d(TAG, "FileSynthesisRequest.done()");
    FileChannel fileChannel = null;

    int sampleRateInHz = 0;
    int audioFormat = 0;
    int channelCount = 0;

    synchronized (mStateLock) {
        if (mDone) {
            Log.w(TAG, "Duplicate call to done()");
            // This is not an error that would prevent synthesis. Hence no
            // setStatusCode is set.
            return TextToSpeech.ERROR;
        }
        if (mStatusCode == TextToSpeech.STOPPED) {
            if (DBG) Log.d(TAG, "Request has been aborted.");
            return errorCodeOnStop();
        }
        if (mStatusCode != TextToSpeech.SUCCESS && mStatusCode != TextToSpeech.STOPPED) {
            mDispatcher.dispatchOnError(mStatusCode);
            return TextToSpeech.ERROR;
        }
        if (mFileChannel == null) {
            Log.e(TAG, "File not open");
            return TextToSpeech.ERROR;
        }
        mDone = true;
        fileChannel = mFileChannel;
        sampleRateInHz = mSampleRateInHz;
        audioFormat = mAudioFormat;
        channelCount = mChannelCount;
    }

    try {
        // Write WAV header at start of file
        fileChannel.position(0);
        int dataLength = (int) (fileChannel.size() - WAV_HEADER_LENGTH);
        fileChannel.write(
                makeWavHeader(sampleRateInHz, audioFormat, channelCount, dataLength));

        synchronized (mStateLock) {
            closeFile();
            mDispatcher.dispatchOnSuccess();
            return TextToSpeech.SUCCESS;
        }
    } catch (IOException ex) {
        Log.e(TAG, "Failed to write to output file descriptor", ex);
        synchronized (mStateLock) {
            cleanUp();
        }
        return TextToSpeech.ERROR;
    }
}