Example usage for java.nio.channels FileChannel write

List of usage examples for java.nio.channels FileChannel write

Introduction

In this page you can find the example usage for java.nio.channels FileChannel write.

Prototype

public final long write(ByteBuffer[] srcs) throws IOException 

Source Link

Document

Writes a sequence of bytes to this channel from the given buffers.

Usage

From source file:org.wso2.carbon.mediation.library.service.upload.LibraryUploader.java

private void writeResource(DataHandler dataHandler, String tempDestPath, String destPath, String fileName)
        throws IOException {

    File tempDestFile = new File(tempDestPath, fileName);
    FileChannel out = null;
    FileChannel in = null;//from   w w  w .j  a  va 2 s.  co m
    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(tempDestFile);
        dataHandler.writeTo(fos);
        fos.flush();

        /* File stream is copied to a temp directory in order handle hot deployment issue
           occurred in windows */
        dataHandler.writeTo(fos);
        out = new FileOutputStream(destPath + File.separator + fileName).getChannel();
        in = new FileInputStream(tempDestFile).getChannel();
        out.write(in.map(FileChannel.MapMode.READ_ONLY, 0, in.size()));
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            log.warn("Can't close file streams.", e);
        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            log.warn("Can't close file streams.", e);
        }
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (IOException e) {
            log.warn("Can't close file streams.", e);
        }
    }

    if (!tempDestFile.delete()) {
        if (log.isDebugEnabled()) {
            log.debug("temp file: " + tempDestFile.getAbsolutePath()
                    + " deletion failed, scheduled deletion on server exit.");
        }
        tempDestFile.deleteOnExit();
    }
}

From source file:org.apache.camel.component.file.FileOperations.java

private void writeFileByStream(InputStream in, File target) throws IOException {
    FileChannel out = null;
    try {/*  w w  w  . j  ava  2 s . c om*/
        out = prepareOutputFileChannel(target, out);

        if (LOG.isTraceEnabled()) {
            LOG.trace("Using InputStream to transfer from: " + in + " to: " + out);
        }
        int size = endpoint.getBufferSize();
        byte[] buffer = new byte[size];
        ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            if (bytesRead < size) {
                byteBuffer.limit(bytesRead);
            }
            out.write(byteBuffer);
            byteBuffer.clear();
        }
    } finally {
        IOHelper.close(in, target.getName(), LOG);
        IOHelper.close(out, target.getName(), LOG);
    }
}

From source file:org.apache.hadoop.yarn.server.security.CertificateLocalizationService.java

private void writeX509ToLocalFS(ByteBuffer keyStore, File keyStoreLocation, ByteBuffer trustStore,
        File trustStoreLocation, String password, File passwordFileLocation) throws IOException {
    FileChannel keyStoreChannel = new FileOutputStream(keyStoreLocation, false).getChannel();
    keyStoreChannel.write(keyStore);
    keyStoreChannel.close();//from w  w w. ja v a 2 s .c  o m

    FileChannel trustStoreChannel = new FileOutputStream(trustStoreLocation, false).getChannel();
    trustStoreChannel.write(trustStore);
    trustStoreChannel.close();

    FileUtils.writeStringToFile(passwordFileLocation, password);
}

From source file:it.geosolutions.opensdi2.service.impl.FileUploadServiceImpl.java

/**
 * Create a temporal file with a byte array
 * /*ww w . j av  a 2s .c om*/
 * @param key of the file
 * @param bytes to write
 * @param i index by the file name
 * @return absolute path to the file
 * @throws IOException
 */
public String createTemporalFile(String key, byte[] bytes, int i) throws IOException {

    String filePath = temporaryFolder + File.separator + key;

    try {

        // write bytes
        File tmpFile = new File(filePath);

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Appending bytes to " + tmpFile.getAbsolutePath());
        }

        // File channel to append bytes
        @SuppressWarnings("resource")
        FileChannel channel = new FileOutputStream(tmpFile, true).getChannel();
        ByteBuffer buf = ByteBuffer.allocateDirect((int) bytes.length);

        // put bytes
        buf.put(bytes);

        // Flips this buffer.  The limit is set to the current position and then
        // the position is set to zero.  If the mark is defined then it is discarded.
        buf.flip();

        // Writes a sequence of bytes to this channel from the given buffer.
        channel.write(buf);

        // close the channel
        channel.close();

    } catch (IOException e) {
        LOGGER.error("Error writing file bytes", e);
    }

    return filePath;
}

From source file:org.neo4j.io.pagecache.impl.SingleFilePageSwapper.java

private long lockPositionWriteVector(long filePageId, FileChannel channel, long fileOffset, ByteBuffer[] srcs)
        throws IOException {
    try {//from  w  w w.ja  va  2  s  .  c om
        long toWrite = filePageSize * (long) srcs.length;
        long bytesWritten = 0;
        synchronized (positionLock(channel)) {
            channel.position(fileOffset);
            do {
                bytesWritten += channel.write(srcs);
            } while (bytesWritten < toWrite);
            return bytesWritten;
        }
    } catch (ClosedChannelException e) {
        // AsynchronousCloseException is a subclass of
        // ClosedChannelException, and ClosedByInterruptException is in
        // turn a subclass of AsynchronousCloseException.
        tryReopen(filePageId, e);
        boolean interrupted = Thread.interrupted();
        // Recurse because this is hopefully a very rare occurrence.
        channel = unwrappedChannel(filePageId);
        long bytesWritten = lockPositionWriteVector(filePageId, channel, fileOffset, srcs);
        if (interrupted) {
            Thread.currentThread().interrupt();
        }
        return bytesWritten;
    }
}

From source file:eu.stratosphere.nephele.services.iomanager.IOManagerPerformanceBenchmark.java

@SuppressWarnings("resource")
private final void speedTestNIO(int bufferSize, boolean direct) throws IOException {
    final Channel.ID tmpChannel = ioManager.createChannel();

    File tempFile = null;//from   www. j  ava  2 s.c  o m
    FileChannel fs = null;

    try {
        tempFile = new File(tmpChannel.getPath());

        RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
        fs = raf.getChannel();

        ByteBuffer buf = direct ? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize);

        long writeStart = System.currentTimeMillis();

        int valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            if (buf.remaining() < 4) {
                buf.flip();
                fs.write(buf);
                buf.clear();
            }
            buf.putInt(valsLeft);
        }

        if (buf.position() > 0) {
            buf.flip();
            fs.write(buf);
        }

        fs.close();
        raf.close();
        fs = null;

        long writeElapsed = System.currentTimeMillis() - writeStart;

        // ----------------------------------------------------------------

        raf = new RandomAccessFile(tempFile, "r");
        fs = raf.getChannel();
        buf.clear();

        long readStart = System.currentTimeMillis();

        fs.read(buf);
        buf.flip();

        valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            if (buf.remaining() < 4) {
                buf.compact();
                fs.read(buf);
                buf.flip();
            }
            if (buf.getInt() != valsLeft) {
                throw new IOException();
            }
        }

        fs.close();
        raf.close();

        long readElapsed = System.currentTimeMillis() - readStart;

        LOG.info("NIO Channel with buffer " + bufferSize + ": write " + writeElapsed + " msecs, read "
                + readElapsed + " msecs.");
    } finally {
        // close if possible
        if (fs != null) {
            fs.close();
            fs = null;
        }
        // try to delete the file
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:eu.stratosphere.nephele.taskmanager.runtime.EnvelopeConsumptionLog.java

private void writeAnnouncedEnvelopesBufferToDisk() {

    FileChannel fc = null;

    try {//  w  ww. ja  v  a  2s.  c o  m

        this.announcedEnvelopesAsIntBuffer.flip();
        this.announcedEnvelopesAsByteBuffer
                .position(this.announcedEnvelopesAsIntBuffer.position() * SIZE_OF_INTEGER);
        this.announcedEnvelopesAsByteBuffer.limit(this.announcedEnvelopesAsIntBuffer.limit() * SIZE_OF_INTEGER);

        fc = new FileOutputStream(this.logFile, true).getChannel();

        while (this.announcedEnvelopesAsByteBuffer.hasRemaining()) {
            fc.write(this.announcedEnvelopesAsByteBuffer);
        }

    } catch (IOException ioe) {
        LOG.error(StringUtils.stringifyException(ioe));
    } finally {

        if (fc != null) {
            try {
                fc.close();
            } catch (IOException ioe) {
            }
        }

        this.announcedEnvelopesAsIntBuffer.clear();
        this.announcedEnvelopesAsByteBuffer.clear();
    }

}

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);//ww  w  .  j av a 2s.  co 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:sos.scheduler.editor.app.WebDavDialogListener.java

public void deleteProfile(String profilename) throws Exception {
    try {//  w  w  w  .  ja  v a  2s.  co m
        setCurrProfileName(profilename);
        //java.util.Properties profile = getCurrProfile();
        String filename = configFile;

        byte[] b = getBytesFromFile(new File(filename));
        String s = new String(b);
        //System.out.println(s);

        int pos1 = s.indexOf("[" + PREFIX + " " + profilename + "]");
        int pos2 = s.indexOf("[", pos1 + 1);

        if (pos1 == -1) {
            //System.out.println("profile nicht gefunden");
            pos1 = s.length();
            pos2 = -1;
            return;
        }

        if (pos2 == -1)
            pos2 = s.length();

        String s2 = s.substring(0, pos1) + s.substring(pos2);

        java.nio.ByteBuffer bbuf = java.nio.ByteBuffer.wrap(s2.getBytes());

        java.io.File file = new java.io.File(filename);

        boolean append = false;

        java.nio.channels.FileChannel wChannel = new java.io.FileOutputStream(file, append).getChannel();

        wChannel.write(bbuf);

        wChannel.close();

    } catch (java.io.IOException e) {

        try {
            new ErrorLog("error in " + sos.util.SOSClassUtil.getMethodName() + " ; could not delete profile="
                    + profilename, e);
        } catch (Exception ee) {
            //tu nichts
        }
        hasError = true;
        throw new Exception(e.getMessage());

    } finally {

        cboConnectname.setItems(getProfileNames());
        cboConnectname.setText(currProfileName);
        txtURL.setText(currProfile.getProperty("url"));
    }

}