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:jackpal.androidterm.Term.java

private void copyClipboardToFile(String filename) {
    if (filename == null)
        return;//from w w w  . j a  v  a  2 s.  c o  m
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(filename);
        FileChannel fc = fos.getChannel();
        try {
            ClipboardManagerCompat clip = ClipboardManagerCompatFactory.getManager(getApplicationContext());
            if (clip.hasText()) {
                ByteBuffer by = ByteBuffer.wrap(clip.getText().toString().getBytes());
                fc.write(by);
            }
            fc.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:au.org.theark.core.service.ArkCommonServiceImpl.java

/**
 * {@inheritDoc}// ww  w. j  a  va2s .c om
 */
public void copyArkLargeFileAttachments(String sourceFilePath, String destinationFilePath) throws IOException {
    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(new File(sourceFilePath)).getChannel();
        destination = new FileOutputStream(new File(destinationFilePath)).getChannel();

        // This fails with Map Failed exception on large files
        // destination.transferFrom(source, 0, source.size());

        ByteBuffer buf = ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE);
        while ((source.read(buf)) != -1) {
            buf.flip();
            destination.write(buf);
            buf.clear();
        }
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:com.clustercontrol.agent.job.PublicKeyThread.java

/**
 *  ?Authorized_key????<BR>//from   w w w  .j a v  a2 s. c  o m
 * 
 * @param publicKey
 * @return true : ?false:
 */
private synchronized boolean deleteKey(String publicKey) {
    m_log.debug("delete key start");

    if (SKIP_KEYFILE_UPDATE) {
        m_log.info("skipped deleting publicKey");
        return true;
    }

    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    CharsetDecoder decoder = charset.newDecoder();

    //???
    String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH);
    if (fileName == null || fileName.length() == 0)
        return false;

    //File?
    File fi = new File(fileName);

    RandomAccessFile randomAccessFile = null;
    FileChannel channel = null;
    FileLock lock = null;
    boolean delete = false;
    try {
        //RandomAccessFile?
        randomAccessFile = new RandomAccessFile(fi, "rw");
        //FileChannel?
        channel = randomAccessFile.getChannel();

        // 
        for (int i = 0; i < (FILELOCK_TIMEOUT / FILELOCK_WAIT); i++) {
            if (null != (lock = channel.tryLock())) {
                break;
            }
            m_log.info("waiting for locked file... [" + (i + 1) + "/" + (FILELOCK_TIMEOUT / FILELOCK_WAIT)
                    + " : " + fileName + "]");
            Thread.sleep(FILELOCK_WAIT);
        }
        if (null == lock) {
            m_log.warn("file locking timeout.");
            return false;
        }

        // (?)
        synchronized (authKeyLock) {
            //??
            ByteBuffer buffer = ByteBuffer.allocate((int) channel.size());

            //??
            channel.read(buffer);

            // ???????????0?
            buffer.flip();

            //??
            String contents = decoder.decode(buffer).toString();

            // ?
            m_log.debug("contents " + contents.length() + " : " + contents);

            //??
            List<String> keyCheck = new ArrayList<String>();
            StringTokenizer tokenizer = new StringTokenizer(contents, "\n");
            while (tokenizer.hasMoreTokens()) {
                keyCheck.add(tokenizer.nextToken());
            }

            //??????
            int s = keyCheck.lastIndexOf(publicKey);
            if (s != -1) {
                // ?
                m_log.debug("remobe key : " + keyCheck.get(s));
                keyCheck.remove(s);
            }

            //?????
            encoder.reset();
            buffer.clear();

            int i;
            if (keyCheck.size() > 0) {
                for (i = 0; i < keyCheck.size() - 1; i++) {
                    encoder.encode(CharBuffer.wrap(keyCheck.get(i) + "\n"), buffer, false);
                }
                encoder.encode(CharBuffer.wrap(keyCheck.get(i)), buffer, true);
            }

            //???
            buffer.flip();
            channel.truncate(0);
            channel.position(0);
            channel.write(buffer);
        }

        delete = true;
    } catch (IOException e) {
        m_log.error(e.getMessage(), e);
    } catch (RuntimeException e) {
        m_log.error(e.getMessage(), e);
    } catch (InterruptedException e) {
        m_log.error(e.getMessage(), e);
    } finally {
        try {
            if (channel != null) {
                channel.close();
            }
            if (randomAccessFile != null) {
                randomAccessFile.close();
            }
            //?
            if (lock != null) {
                lock.release();
            }
        } catch (Exception e) {
        }
    }

    return delete;
}

From source file:edu.harvard.iq.dvn.core.web.ExploreDataPage.java

private void writeFile(File fileIn, char[] charArrayIn, int bufSize) {
    try {/*from  w ww  .  java2s. c  om*/

        FileOutputStream outputFile = null;
        outputFile = new FileOutputStream(fileIn, true);
        FileChannel outChannel = outputFile.getChannel();
        ByteBuffer buf = ByteBuffer.allocate((bufSize * 2) + 1000);
        for (char ch : charArrayIn) {
            buf.putChar(ch);
        }

        buf.flip();

        try {
            outChannel.write(buf);
            outputFile.close();
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }

    } catch (IOException e) {
        throw new EJBException(e);
    }

}

From source file:com.MainFiles.Functions.java

public int createStan() {
    int x = 0;/*  w  ww  .ja  va  2 s  .  com*/

    String filename = COUNT_FILE;
    File inwrite = new File(filename);

    // Get a file channel for the file
    try {
        FileChannel channel = new RandomAccessFile(inwrite, "rw").getChannel();
        // Use the file channel to create a lock on the file.
        // This method blocks until it can retrieve the lock.
        FileLock lock = channel.lock();
        //  if(!inwrite.exists()) {
        String s = "";
        try {
            int fileSize = (int) channel.size();
            //    System.out.println("int is" + fileSize);
            ByteBuffer bafa = ByteBuffer.allocate(fileSize);
            int numRead = 0;
            while (numRead >= 0) {
                numRead = channel.read(bafa);
                bafa.rewind();
                for (int i = 0; i < numRead; i++) {
                    int b = (int) bafa.get();
                    char c = (char) b;
                    s = s + c;
                }
            }

            x = Integer.parseInt(s);
            if (x > 999999) {
                x = 100000;
            } else if (x < 100000) {
                x = 100000;
            }
            x = ++x;
            String xx = String.valueOf(x);
            byte[] yy = xx.getBytes();
            channel.truncate(0);
            channel.write(ByteBuffer.wrap(yy));
            // channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        lock.release();
        // Close the file
        channel.close();
    } catch (FileNotFoundException e) {
        String message = "The file " + inwrite.getName() + " does not exist. So no input can be written on it";
        System.out.println(message);
        e.printStackTrace();
        //log to error file
    } catch (IOException e) {
        System.out.println("Problem writing to the logfile " + inwrite.getName());

    }

    filename = "";
    return x;
}

From source file:org.alfresco.repo.search.impl.lucene.index.IndexInfo.java

private void writeStatusToFile(FileChannel channel) throws IOException {
    long size = getBufferSize();

    ByteBuffer buffer;/*  ww w .ja  va2  s.  co m*/
    if (useNIOMemoryMapping) {
        MappedByteBuffer mbb = channel.map(MapMode.READ_WRITE, 0, size);
        mbb.load();
        buffer = mbb;
    } else {
        channel.truncate(size);
        buffer = ByteBuffer.wrap(new byte[(int) size]);
    }

    buffer.position(0);

    buffer.putLong(version);
    CRC32 crc32 = new CRC32();
    crc32.update((int) (version >>> 32) & 0xFFFFFFFF);
    crc32.update((int) (version >>> 0) & 0xFFFFFFFF);

    buffer.putInt(indexEntries.size());
    crc32.update(indexEntries.size());

    for (IndexEntry entry : indexEntries.values()) {
        String entryType = entry.getType().toString();
        writeString(buffer, crc32, entryType);

        writeString(buffer, crc32, entry.getName());

        writeString(buffer, crc32, entry.getParentName());

        String entryStatus = entry.getStatus().toString();
        writeString(buffer, crc32, entryStatus);

        writeString(buffer, crc32, entry.getMergeId());

        buffer.putLong(entry.getDocumentCount());
        crc32.update((int) (entry.getDocumentCount() >>> 32) & 0xFFFFFFFF);
        crc32.update((int) (entry.getDocumentCount() >>> 0) & 0xFFFFFFFF);

        buffer.putLong(entry.getDeletions());
        crc32.update((int) (entry.getDeletions() >>> 32) & 0xFFFFFFFF);
        crc32.update((int) (entry.getDeletions() >>> 0) & 0xFFFFFFFF);

        buffer.put(entry.isDeletOnlyNodes() ? (byte) 1 : (byte) 0);
        crc32.update(entry.isDeletOnlyNodes() ? new byte[] { (byte) 1 } : new byte[] { (byte) 0 });
    }
    buffer.putLong(crc32.getValue());

    if (useNIOMemoryMapping) {
        ((MappedByteBuffer) buffer).force();
    } else {
        buffer.rewind();
        channel.position(0);
        channel.write(buffer);
    }
}